Node JS AWS S3 file upload. How to get public URL response

旧时模样 提交于 2019-12-03 05:46:21

问题


I'm uploading a file to Amazon S3 using the Node SDK.

The file uploads are working fine, but I want to get the public url of the file to send back to the client.

At the moment the response I get is:

Successfully uploaded data { ETag: '"957cd1a335adf5b4000a5101ec1f52bf"' }

Here is my code. I'm using a Node Express server, and Multer to handle uploads.

app.use(multer({ // https://github.com/expressjs/multer
      dest: './public/uploads/', 
      limits : { fileSize:100000 },
      rename: function (fieldname, filename) {
        var time = new Date().getTime();
        return filename.replace(/\W+/g, '-').toLowerCase() + time;
      },
      onFileUploadData: function (file, data, req, res) {
        // file : { fieldname, originalname, name, encoding, mimetype, path, extension, size, truncated, buffer }
        var params = {
          Bucket: creds.awsBucket,
          Key: file.name,
          Body: data,
          ACL: 'public-read'
        };

        var s3 = new aws.S3()
        s3.putObject(params, function (perr, pres) {
          if (perr) {
            console.log("Error uploading data: ", perr);
          } else {
            console.log("Successfully uploaded data", pres);
          }
        });
      }
    }));

    app.post('/upload-image', function(req, res){
        if(req.files.file === undefined){
            res.send("error, no file chosen");
        }
    });

回答1:


Use upload instead of putObject. It will return public url in Location key



来源:https://stackoverflow.com/questions/30763448/node-js-aws-s3-file-upload-how-to-get-public-url-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!