我想從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'服務,也許我會弄清楚這一點。 –