2013-02-15 3 views
3

내 요청에 따라 클라이언트의 파일 내용을 보내려고하지만 Express의 유일한 문서는 실제 파일을 필요로하는 다운로드 기능입니다. 내가 보내려하는 파일은 S3에서 나옵니다. 따라서 파일 이름과 내용 만 있으면됩니다.Nodejs Express 파일 보내기

콘텐츠 유형 및 파일 이름과 파일의 콘텐츠에 해당하는 파일의 콘텐츠를 보내려면 어떻게해야합니까? 예를 들어

: 파일의 종류는 분명히 파일에 따라

files.find({_id: id}, function(e, o) { 
    client.getObject({Bucket: config.bucket, Key: o.key}, function(error, data) { 
    res.send(data.Body); 
    }); 
}); 
+0

에 파이프 파일에 필요한 헤더를 설정하는주의해야 .html # res.download) –

답변

7

.

http://en.wikipedia.org/wiki/Internet_media_type

정확히 파일이 무엇인지 알고 있다면

, 다음 (하지만 필수는 아닙니다) 응답이 중 하나를 지정 : 이것 좀 보라. 파일의 길이를 응답에 추가해야합니다 (가능한 경우, 즉 스트림이 아닌 경우). 첨부 파일로 다운로드 할 수있게하려면 Content-Disposition 헤더를 추가하십시오. 따라서 모두를 추가하면됩니다.

var filename = "myfile.txt"; 
res.set({ 
    "Content-Disposition": 'attachment; filename="'+filename+'"', 
    "Content-Type": "text/plain", 
    "Content-Length": data.Body.length 
}); 

참고 : Express 3.x를 사용하고 있습니다.

EDIT : 사실 Express는 콘텐츠 길이를 계산할만큼 똑똑하기 때문에 Content-Length 헤더를 추가 할 필요가 없습니다.

0

스트림을 사용하는 것이 좋습니다. knox 라이브러리를 사용하면 작업을 단순화 할 수 있습니다. 로컬 당신이`res.download` (http://expressjs.com/api를 사용할 수있는 파일을 저장하는 경우 녹스 클라이언트

var inspect = require('eyespect').inspector(); 
var knox = require('knox'); 
var client = knox.createClient({ 
    key: 's3KeyHere' 
    , secret: 's3SecretHere' 
    , bucket: 's3BucketHer' 
}); 
/** 
* @param {Stream} response is the response handler provided by Express 
**/ 
function downloadFile(request, response) { 
    var filePath = 's3/file/path/here'; 
    client.getFile(filePath, function(err, s3Response) { 
    s3Response.pipe(response); 
    s3Response.on('error', function(err){ 
     inspect(err, 'error downloading file from s3'); 
    }); 

    s3Response.on('progress', function(data){ 
     inspect(data, 's3 download progress'); 
    }); 
    s3Response.on('end', function(){ 
     inspect(filePath, 'piped file to remote client successfully at s3 path'); 
    }); 
    }); 
} 

npm install knox eyespect