简体   繁体   中英

Upload a file to Amazon S3 with NodeJS and S3FS/multiparty

i am using multiparty and S3FS to upload files to amazon s3 ,when writing a file stream to s3 it creates the temp file path along with bucket path,for example :

var S3FS = require('s3fs');
var s3fsImpl = new S3FS('my-bucket/files',{
    accessKeyId: config.amazonS3.accessKeyId,
    secretAccessKey: config.amazonS3.secretAccessKey
});

module.exports = function (app) {
    app.post('/upload', function (req, resp) {

        // get the file location
        var file = req.files.file;
        var stream = fs.createReadStream(file.path);


            return s3fsImpl.writeFile(fileName,stream).then(function(){
                fs.unlink(file.path,function(err){
                    if(err)
                        console.error(err);
                });

                resp.send('done');

            }).catch(function (err) {
                return resp.status(500).send({
                    message: errorHandler.getErrorMessage(err)
                });
            });

    });
};

The file should be written in s3 in path :

my-bucket/files

while now it's writing the temp file path in amazon s3 bucket:

my-bucket/files/home/ubuntu/www/html/sampleProject/public/files

any idea why temp file path 'home/ubuntu/www/html/sampleProject/public/files' get created inside s3 bucket when writing the file?

i found the solution myself ,the file name i was sending to write file was wrong , i only replaced \\ with / when getting the file name from temp path.

var filePath= 'home\ubuntu\www\html\sampleProject\public\files\myfile.jpg'.replace(/\\/g, '/');

var fileName = filePath.substr(filePath.lastIndexOf('/')+1,filePath.length-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM