开发者

html5 multiple upload along with ajax

I am trying to use the multiple upload attribute of HTML5 to upload files. I know it wouldn't work with IE and fall back to single file upload. also I found some invalid html tag like min max allows opera to do the same.

I am trying to do the following: The browse button be capable of selecting multiple files. But the ajax should send files one by one. My scenario is something like this: the user selects 5 files and starts the upload . Now the ajax should firstfile send th开发者_Python百科e first file, then second, and so on. The server side script does something with the file and returns some data. now as soon as one file upload is completed it must render that part of the result. So as the user selects images and starts uploading the results come out as soon as each file is uploaded (and not after all the files are uploaded).

I tried something like this :

 function handleFiles(files)
  { alert(files.length); //properly returns the number of files selected
    for (var i = 0; i < files.length; i++) {
  new FileUpload(files[i])
  }
  }

  function FileUpload(file) {
  var reader = new FileReader();

  var xhr = new XMLHttpRequest();
  this.xhr = xhr;

  xhr.open("POST", "portfolio/add_media");
  reader.onload = function(evt) {
    xhr.sendAsBinary(evt.target.result);
  };
  reader.readAsBinaryString(file);
}

after reading the tutorial at mozilla but I end up with missing params.

. so can some one suggest me a clean solution to this

Some more details : When I pass a single file ( with no multiple attribute ) my server recieves :

"image"=>[# < ActionDispatch::Http::UploadedFile:0x10d55be8 @tempfile=#< File:C:/Users/Gaurav/AppData/Local/Temp/RackMultipart20110701-1916-2ly4k2-0>, @headers="Content-Disposition: form-data; name=\"picture[image][]\"; filename=\"Desert.jpg\"\r\nContent-Type: image/jpeg\r\n", @content_type="image/jpeg", @original_filename="Desert.jpg">]}}

But when I use multiple attribute and send using xhr I am able to get only one file param. How do I get the rest of the params ? esp the action dispatch thingy


You are simply sending the file data to the server, without encoding it in any way. For the server to know how to process it you need to encode your data properly (multipart/form-data encoding). Easiest way is using a FormData object: https://developer.mozilla.org/En/Using_XMLHttpRequest#Sending_files_using_a_FormData_object. Only that instead of data.append("CustomField", "This is some extra data") you would write data.append("file1", event.target.result).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜