Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer Core-Ajax File upload

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?

like image 524
Eik W. Avatar asked Aug 02 '14 22:08

Eik W.


1 Answers

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

like image 66
ebidel Avatar answered Oct 11 '22 23:10

ebidel