2016-10-02 34 views
5

我想从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方法被调用后。 有谁知道这是为什么发生,或者如果我应该使用不同的方法?

感谢

回答

3

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); 
} 
+0

感谢您的回答。我确实能够使用您的代码对文件进行编码和发送。我也会看看'authAjax'服务,也许我会弄清楚这一点。 –