Question

Using XMLHttpRequest Level 2 I want to upload a File. I am using jQuery so I want to do it using jQuery in preference.

So I wrote the following code (coffescript, but should be easily readable by anyone familiar with javascript)

fileToUpload = event.currentTarget.files[0]

data = new FormData()
data.append("uploadedfile", fileToUpload) 

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    contentType: false,
    processData: false,
    mimeType: 'multipart/form-data',
})

Using that code, on the server side with PHP I do a `

With Firefox 17.0.1 I get nothing. $_FILES is null, With Chromium 22.0 I get the the uploaded file (in a strange format, but at least something)

Array
(
    [uploadedfile] => Array
        (
            [name] => filename.txt
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpWwenhc
            [error] => 0
            [size] => 189
        )

)

Does anyone knows if it is a Firefox bug? Is there a workaround? Am I doing something wrong? I searched for a similar problem, but all suggested answers that I found didn't work with me (were not for Firefox, were not using xhr level 2, etc)

Thanks in advance.

PLEASE: I don't care about IE or older versions. Neither iframes solutions nor plugins. Just XmlHttpRequest Level 2. For those who didn't heard about it take a look at: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects

Was it helpful?

Solution

Remove the mimeType parameter, the browser will generate the correct mime type with the required boundry.

OTHER TIPS

I've just made it. There really is no way of uploading files through AJAX. Better just refer to .php file directly.

You may need to treat the files as an array to get Firefox and PHP to understand. Try changing the name of the upload field:

data.append("uploadedfiles[]", fileToUpload);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top