gpt4 book ai didi

javascript - 使用nodejs上传大文件

转载 作者:搜寻专家 更新时间:2023-11-01 00:09:17 26 4
gpt4 key购买 nike

我有以下 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() block 之后写入的最后几条日志。

过去几天我一直在努力尝试理解为什么它适用于小文件而不适用于大文件。我没有看到任何超时,代码似乎一直挂起,直到我将其关闭。

谁能指导我做错了什么?

更新:

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 是一个字符串数组,还是一个数组数组?

此外,您将其作为 multipart/form-data 发布,这意味着您必须将数据修改为该格式。您这样做了吗,或者 post_data 只是文件中的原始数据?

关于javascript - 使用nodejs上传大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6664232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com