Polymer Core-Ajax File upload

五迷三道 提交于 2019-12-30 09:53:52

问题


i want to upload a file from a form with core-ajax. Right now it my code looks like this:

<core-ajax 
  auto="false"
  method="POST"
  url="/file-upload" 
  handleAs="json"
  on-core-response="{{handleResponse}}"
  contentType="multipart/form-data; boundary=---------------------------7da24f2e50046"
  params="{{item}}"
  id="ajax"></core-ajax>

<form>
 <input type="text" name="Name" id="name"></br>
 <label class="formLine">File</label></br>
 <input type="file" name="File" id="file"></br>
 <paper-button raisedbutton="" label="send" role="button" aria-label="disabled" class="formLine" on-tap="{{click}}"></paper-button>
</form>

with the following javascript-code:

click: function(){
var name = this.$.name;
var File = this.$.file;

this.item = {
  'Name': name.value,
  'File':File.value
  };
this.$.ajax.go();
}

So when i send the request there is no data to process. In the previous version i handled this with a regular form and used multiparty to parse the request.

How should i send and handle the data?


回答1:


core-ajax doesn't make file upload that easy. It provides a few defaults that are geared more towards simpler requests with key/val params.

There's a couple of different ways to send file/blob data using XHR2. core-ajax sets a default contentType of application/x-www-form-urlencoded (code). Instead, you want to override that and allow the browser to set its own content-type to create a mime multipart requrst. Here, I'm using FormData() to do that:

<input type="file" name="File" id="file" on-change="{{setFiles}}">

<core-ajax id="ajax" url="/file-upload" method="POST"
           handleAs="json" response="{{response}}"></core-ajax>

...

setFiles: function(e, detail, sender) {
  var formData = new FormData();

  for (var i = 0, f; f = sender.files[i]; ++i) {
    formData.append(sender.name, f,
                    this.$.name.value || f.name);
  }

  this.$.ajax.body = formData;
  // Override default type set by core-ajax.
  // Allow browser to set the mime multipart content type itself. 
  this.$.ajax.contentType = null;
},
upload: function(e, detail, sender) {
  if (!this.$.file.files.length) {
    alert('Please include a file');
    return;
  }
  this.$.ajax.go();
},

Demo: http://jsbin.com/himetoco/1/edit



来源:https://stackoverflow.com/questions/25099938/polymer-core-ajax-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!