0

I want to ulpload JSON and txt files to the server with a size of 200KB.

This is the script I'm using:

$allowedExts = array("json", "txt");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "application/json")
        || ($_FILES["file"]["type"] == "text/txt"))
    && ($_FILES["file"]["size"] < 200000)
    && in_array($extension, $allowedExts)
) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Código do erro: " . $_FILES["file"]["error"] . "<br>";
    } else {
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
        move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload" . $_FILES["file"]["name"]);
        echo "Gravado em: " . $diretorio . $_FILES["file"]["name"];
    }
} else {
    echo "Invalid file.";
}

But I always get the "Invalid file" error. Why is it?

immulatin
  • 2,118
  • 1
  • 12
  • 13

2 Answers2

1

You aren't actually ever submitting your form. Your javascript simply loads a new page in the browser window (upload.php) when you change the value of upload field.

Please read this article on how to upload files using jQuery, as it is not as straightforward as one would hope.

How can I upload files asynchronously?

Or, if your intent is to actually redirect to this a new page (rather than upload a file without reload of page in browser), then you can simply do a traditional non-AJAX form for the file upload as is outlined in the answer by @OlafErlandsen here.

Community
  • 1
  • 1
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Thanks, the idea is to upload the file asynchronously, I didn't expect it to be this difficult. The article will help me solve the problem. –  Oct 09 '13 at 22:39
0

in your HTML form use enctype:

<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

And use this content type( to avoid problems ):

$types = array('application/json','application/x-javascript','text/javascript','text/x-javascript','text/x-json');
if( in_array( $_FILES['file']['type'] , $types ) )

And, if you use jQuery:

var formData = new FormData($('form')[0]);
$.ajax({
    url: 'file.php',
    type: 'POST',
    success: function ( response ){ console.log( "ok" ); },
    data: formData,
    cache: false,
    contentType: false,
    enctype: 'multipart/form-data',
    processData: false
});

And, try upload with this class:

https://github.com/erlandsen/upload

Good Luck!

Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73