简体   繁体   中英

Upload a file to AWS S3 using node js and Postman

I am new to AWS,and trying to figure out how to upload a file using the AWS S3 API ( http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html ), which is incorporated in my own api.

I can create a bucket, and get a list of all the buckets- however I am struggling with a file upload.

This is by code:

router.post('/upload', function(req, res, next) {
    var params = {
        Bucket: req.body.bucketName,
        Key: req.body.key,
        Body: req.body.body
    }
    s3.putObject(params, function(err, data) {
        if (err) {
            return next(err)
        } else {
            res.json(data)
        }
    })
})

So when I run my server, I try to make a post request using postman to localhost:8080/upload with the following: attaching a file, and the key and body - but I think I do this part wrong. 邮递员视图

And I also attach the file:

在此处输入图片说明

Question is:

Do I correctly understand the following- Bucket = the bucket name I want to upload to, Key = the file name, Body = the file contents?

If yes, how do I get this to upload to S3 bucket, as with the current code I get a file added to s3 called ' text.txt ' with the contents ' heello ' rather than my ' test.txt ' file.

are you trying to upload a file correct? So you should use a multipart/form-data content-type, and in body you can point to your file buffer.

In my case, I use with swagger:

upload: (req, res) => {
  const params = {
    Bucket: 'bucket-name',
    Key: req.swagger.params.file.value.originalname,
    ACL: 'public-read',
    Body: req.swagger.params.file.value.buffer
  };

  s3.putObject(params, function(err, data) {
    if (err) {
      console.log('Error uploading image: ', err);
      res.status(500).json().end();
    } else {
      res.status(200).json('File is uploaded').end();
    }
  })
}

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