将Blob转换为文件并将其作为POST参数XMLHttpRequest传递

时间:2012-10-17 15:23:29

标签: ajax xmlhttprequest filereader

//photo - image in Blob type
//no problems with it, checked with FileReader.readAsDataURL & <img>
var form = new FormData()
form.append('file1', photo, 'image.jpg')
ajax.post(url, form, callback) //no photos uploaded

我要做的事情的文档:Uploading Files to the VK Server Procedure(第2步)

那么,我应该如何将我的blob作为POST参数传递?

Image of the request

1 个答案:

答案 0 :(得分:2)

Mozilla开发者网络上的完整文件上载示例

https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Uploading_a_user-selected_file

您使用FileReader.readAsBinaryString()来读取数据,然后使用XHR sendAsBinary()来推送IO

function FileUpload(img, file) {
  var reader = new FileReader(); 
  this.ctrl = createThrobber(img);
  var xhr = new XMLHttpRequest();
  this.xhr = xhr;

  var self = this;
  this.xhr.upload.addEventListener("progress", function(e) {
        if (e.lengthComputable) {
          var percentage = Math.round((e.loaded * 100) / e.total);
          self.ctrl.update(percentage);
        }
      }, false);

  xhr.upload.addEventListener("load", function(e){
          self.ctrl.update(100);
          var canvas = self.ctrl.ctx.canvas;
          canvas.parentNode.removeChild(canvas);
      }, false);
  xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
  reader.onload = function(evt) {
    xhr.sendAsBinary(evt.target.result);
  };
  reader.readAsBinaryString(file);
}