我想从Ember Js上传一个带有ajax的csv文件,并在我的Rails应用程序中读取它。 我试过两种不同的方法。在第一个我试图从灰烬发送的文件是这样的:从Ember Js发送CSV文件到Rails使用Ajax
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,[email protected]\nleo, [email protected]\ngigel, [email protected]\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方法被调用后。 有谁知道这是为什么发生,或者如果我应该使用不同的方法?
感谢
感谢您的回答。我确实能够使用您的代码对文件进行编码和发送。我也会看看'authAjax'服务,也许我会弄清楚这一点。 –