簡體   English   中英

Polymer Core-Ajax文件上傳

[英]Polymer Core-Ajax File upload

我想從帶有core-ajax的表單上傳文件。 現在我的代碼看起來像這樣:

<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>

使用以下javascript代碼:

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

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

因此,當我發送請求時,沒有數據要處理。 在以前的版本中,我使用常規表單處理此問題,並使用multiparty來解析請求。

我該如何發送和處理數據?

core-ajax不會使文件上傳變得容易。 它提供了一些默認值,它們更傾向於使用key / val params更簡單的請求。

使用XHR2發送文件/ blob數據有幾種不同的方法。 core-ajax設置application/x-www-form-urlencodedcode )的默認contentType 相反,您希望覆蓋它並允許瀏覽器設置自己的content-type以創建mime multipart requrst。 在這里,我使用FormData()來做到這一點:

<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();
},

演示: http//jsbin.com/himetoco/1/edit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM