我想从核心阿贾克斯形式上传的文件。 现在是我的code是这样的:
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>
与下面的Javascript成为code:
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();
}
所以当我发送请求没有数据要处理。 在previous版本我处理这与常规的形式,用于多方解析请求。
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.
如何发送和处理数据?
核心阿贾克斯不会使文件上传那么容易。它提供了更对与键/ VAL PARAMS简单的请求面向一些默认设置。
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.
有几个不同的方法来使用XHR2 发送文件/ BLOB数据。 核心AJAX
为应用程序/ x-WWW的形式urlen $的默认
( code )。相反,要重写,并允许浏览器设置自己的的contentType
C $ CD 内容类型
来requrst创建一个MIME多。在这里,我使用 FORMDATA()
来做到这一点:
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();
},
演示: http://jsbin.com/himetoco/1/edit