[英]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-urlencoded
( code )的默认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();
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.