我正在尝试从Ember Js上传一个带有ajax的csv文件,并在我的Rails应用程序中读取它。我试过两种不同的方法。在第一个例子中,我试图像这样发送Ember的文件:
submitImport() {
var fd = new FormData();
var file = this.get('files')[0];
fd.append("csv_file", file);
return this.get('authAjax')
.request('/contacts/import/csv', {
method: 'POST',
processData: false,
contentType: false,
data: fd
});
}但问题是,我没有在rails应用程序中获得csv_file param。request.content_type是application/x-www-form-urlencoded,我需要多部分表单。我可以使用reques.raw_post,但是我得到了类似于这个------WebKitFormBoundarymgBynUffnPTUPW3l\r\nContent-Disposition: form-data; name=\"csv_file\"; filename=\"elevatr_import.csv\"\r\nContent-Type: text/csv\r\n\r\ngeorgica,gica@me.com\nleo, leonard@yahoo.com\ngigel, becali@oita.fcsb\n\r\n------WebKitFormBoundarymgBynUffnPTUPW3l--\r\n的东西,我需要以某种方式解析它,而且我不太喜欢这个解决方案。
另一种方法是发送base64编码的文件,然后从Rails中解码它。我试过这个:
`
submitImport() {
var fd = new FormData();
var file = this.get('files')[0];
this.send('getBase64', file);
var encoded_file = this.get('encoded_file');
return this.get('authAjax')
.request('/contacts/import/csv', {
method: 'POST',
data: { csv_file: encoded_file }
});
},
getBase64(file) {
var controller = this;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
controller.set('encoded_file', reader.result);
};
}但出于某种原因,post请求首先提交,然后调用getBase64方法。有没有人知道为什么会发生这种情况,或者我是否应该采用不同的方法?
谢谢
发布于 2016-10-03 01:27:53
FormData
要使用multipart/form-data发送,您有正确的想法并设置正确的选项,但是authAjax或其他东西可能设置了导致冲突的选项,从而导致了application/x-www-form-urlencoded的内容类型。
// this should make a request with a content-type of multipart/form-data
$.ajax({
url: 'upload/destination',
type: 'POST',
data: formDataObj,
contentType: false,
processData: false,
});Base64
在发出请求后读取文件的原因是FileReader异步工作。要将其作为base64编码的字符串发送,您需要等待读取器在启动ajax请求之前完成。您可以通过在onloadend事件之后提出请求来做到这一点。
actions: {
submitImport() {
var file = this.get('files')[0];
this.encodeAndSendFile(file);
},
},
sendFile(base64File) {
return this.get('authAjax')
.request('/contacts/import/csv', {
method: 'POST',
data: { csv_file: encoded_file },
});
},
encodeAndSend(file) {
var controller = this;
var reader = new FileReader();
reader.onloadend = function () {
controller.sendFile(reader.result);
};
reader.readAsDataURL(file);
}https://stackoverflow.com/questions/39822603
复制相似问题