weixin_33686714 2014-08-02 22:22 采纳率: 0%
浏览 50

Polymer Core-Ajax文件上传

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条回答 默认 最新

  • weixin_33743661 2014-08-03 01:30
    关注

    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

    评论

报告相同问题?