Nodejs Express Submission File

I'm trying to send the content of a file to a client in my request, but the only Express documentation is the upload function, which requires a physical file; the file I am trying to upload comes from S3, so all I have is the filename and its contents.

How can I send the file content and the corresponding headers for the content type and file name along with the file content?

For example:

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

      

+3


source to share


2 answers


The file type depends on the file. Look at this:

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

If you know what exactly your file is, then assign one of them to the answer (not necessary though). You should also add the length of the file to the response (if possible, i.e. if it is not a stream). And if you want it to be uploaded as an attachment add the Content-Disposition header. So, in general, you only need to add this:



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

      

NOTE. I am using Express 3.x.

EDIT . In fact, Express is smart enough to calculate the length of the content for you, so you don't need to add a title Content-Length

.

+7


source


This is a great situation to use streams. Use the knox library for simplicity. Knox has to take care of setting up the correct headers for sending files to the client

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

0


source







All Articles