4

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

Fernando
  • 2,131
  • 3
  • 27
  • 46
  • Try removing the `mimeType` parameter – Musa Jan 01 '13 at 18:34
  • @Musa can you post your suggestion as answer so I can mark it as correct? Thanks for your advice. I was so tired looking for answers that I miss that simple fact. – Fernando Jan 01 '13 at 22:05

3 Answers3

2

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

Musa
  • 96,336
  • 17
  • 118
  • 137
0

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

Ivan
  • 437
  • 1
  • 7
  • 17
  • Yes, there is a way in recent times.. (if recent means two years). It have no complete browser support yet but the two that I care does soport it. More on this: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects – Fernando Jan 01 '13 at 20:51
0

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);
mwilcox
  • 4,065
  • 23
  • 20