[英]Upload a large file using nodejs
我有以下 nodejs 代碼,它通過調用服務器端 API (由我編寫)並將文件內容作為多部分請求傳遞來上傳文件。 問題是我的代碼可以完美地處理小文件,但它無法處理大文件(1 MB 或以上)。 我很確定這是我的代碼中的一個問題,但我無法找出它是什么。
// assume file content have been read into post_data array
//Make post
var google = http.createClient(443, host, secure = true);
var filepath = '/v2_0/put_file/';
var GMTdate = (new Date()).toGMTString();
var fileName = encodeURIComponent(destination);
console.log("fileName : " + fileName);
console.log("Path : " + filepath);
var header = {
'Host': host,
'Authorization': 'Basic ' + authStr,
'Content-Type': 'multipart/form-data; boundary=0xLhTaLbOkNdArZ',
'Last-Modified': GMTdate,
'Filename': fileName,
'Last-Access-By': username
};
var request = google.request('POST', filepath, header);
for (var i = 0; i < post_data.length; i++) {
request.write(post_data[i]);
}
request.end();
request.addListener('response', function(response){
var noBytest = 0;
response.setEncoding('utf8');
console.log('STATUS: ' + response);
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
console.log('File Size: ' + response.headers['content-length'] + " bytes.");
從日志中,我看到控制權來自 request.end(); 但我沒有看到在 request.addListener() 塊之后寫入的最后幾條日志。
過去幾天我一直在努力理解為什么它適用於小文件但不適用於大文件。 我沒有看到任何超時,並且代碼似乎被掛起,直到我將其殺死。
誰能指導我我做錯了什么?
更新:
post_data 是一個數組,這就是我正在做的
post_data = [];
console.log('ContentType =' + ContentType + "\n\nEncoding Style =" + encodingStyle);
post_data.push(new Buffer(EncodeFilePart(boundary, ContentType, 'theFile', FileNameOnly), 'ascii'));
var file_contents = '';
var file_reader = fs.createReadStream(filename, {
encoding: encodingStyle
});
file_reader.on('data', function(data){
console.log('in data');
file_contents += data;
});
file_reader.on('end', function(){
post_data.push(new Buffer(file_contents, encodingStyle))
post_data.push(new Buffer("\r\n--" + boundary + "--\r\n", 'ascii'));
...
var request = google.request('POST', filepath, header);
for (var i = 0; i < post_data.length; i++) {
request.write(post_data[i]);
}
我期待您的建議。
您應該將數組或字符串傳遞給 request.write。 post_data 是字符串數組還是 arrays 數組?
此外,您將其發布為 multipart/form-data,這意味着您必須將數據修改為該格式。 你這樣做了,還是 post_data 只是文件中的原始數據?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.