2016-10-02 2 views
5

Ember Js에서 ajax로 csv 파일을 업로드하고 Rails 응용 프로그램에서이 파일을 읽으려고합니다. 두 가지 접근 방식을 시도했습니다.Ajax를 사용하여 Ember Js에서 Rails로 CSV 파일 보내기

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

을하지만 문제는 내가 레일 응용 프로그램에서 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' 서비스에 대해서도 살펴볼 것입니다. 아마도 이것을 알아낼 수있을 것입니다. –

관련 문제