![](/img/trans.png)
[英]Why append rather than write when using knox / node.js to grab file from Amazon s3
[英]Files downloaded from Amazon S3 using Knox and Node.js are corrupt
我正在使用knox訪問我的Amazon S3存儲桶以進行文件存儲。 我存儲各種文件-主要是MS Office和pdf,但可以是二進制文件或任何其他類型。 我還使用快遞 4.13.3和打雜與連接,打雜的流支持; 上傳文件時,我使用busboy進行處理,因此通過knox直接將其傳輸到S3,因此避免了必須先將它們寫入本地磁盤。
文件上傳正常(我可以使用Transmit手動瀏覽和下載它們),但是下載時遇到問題。
為了清楚起見,我不想將文件寫入本地磁盤,而是將其保存在內存緩沖區中。 這是我用來處理GET請求的代碼:
// instantiate a knox object
var s3client = knox.createClient({
key: config.AWS.knox.key,
secret: config.AWS.knox.secret,
bucket: config.AWS.knox.bucket,
region: config.AWS.region
});
var buffer = undefined;
s3client.get(path+'/'+fileName)
.on('response', function(s3res){
s3res.setEncoding('binary');
s3res.on('data', function(chunk){
buffer += chunk;
});
s3res.on('end', function() {
buffer = new Buffer(buffer, 'binary');
var fileLength = buffer.length;
res.attachment(fileName);
res.append('Set-Cookie', 'fileDownload=true; path=/');
res.append('Content-Length', fileLength);
res.status(s3res.statusCode).send(buffer);
});
}).end();
該文件下載到瀏覽器-我正在使用John Culviner的jquery.fileDownload.js-但下載的文件已損壞,無法打開。 如您所見,我正在使用.attachment
設置mime類型的標頭,並為其他標頭設置.append
(使用.set
沒什么區別)。
在Chrome瀏覽器中下載文件時,我看到以下消息:“ Resource interpreted as Document but transferred with MIME type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
”(用於Excel文件),所以express正確設置了標題,並且下載的文件大小與我在查看存儲分區時看到的匹配。
任何想法出什么事了嗎?
看起來內容可能未以二進制形式發送到瀏覽器。 嘗試如下操作:
if (s3Res.headers['content-type']) {
res.type( s3Res.headers['content-type'] );
}
res.attachment(fileName);
s3Res.setEncoding('binary');
s3Res.on('data', function(data){
res.write(data, 'binary');
});
s3Res.on('end', function() {
res.send();
});
它還會在每次傳入數據時一次發送一個數據塊,因此它應該會提高內存效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.