I'm trying to upload a csv file with ajax from Ember Js and read it in my Rails application. I've tried two different approaches. In the first one I tried to send the file from Ember like this:
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
});
}
but the problem is that I don't get the csv_file param in the rails application. The request.content_type is application/x-www-form-urlencoded
and I need multipart form. I could use reques.raw_post but then I get something like this ------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
and I would need to somehow parse this, and I don't really like this solution.
The other approach was to send the file base64 encoded and then decode it from Rails. I've tried this:
`
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);
};
}
But for some reason, the post request is submitted first and only after that the getBase64 method is called. Does anyone knows why is this happening or if I should use a different approach?
Thanks
Aucun commentaire:
Enregistrer un commentaire