唯一ID(键)不会在每次调用后更改,以在AWS S3中上传图片,因此替换了同一图片

时间:2019-09-09 01:02:50

标签: node.js angular amazon-s3 multer-s3

我正在创建一个有角度的应用程序,在其中我从客户端发起POST调用。在服务器端,我使用multer-sharp-s3设置了路由,在该路由中,我会生成一个新名称(密钥),并在每次有呼叫时将其上传到aws s3。

角度html代码:

<form>
<input type="file" name='avatar' id="imageUploadInput" accept="image/*" #profilePicInput (change)="imageUpload(profilePicInput.files)" >
</form>

角度ts文件:

imageUpload(fileList:FileList){
    this.fileToUpload= fileList.item(0);
    let formData = new FormData();
    formData.append('avatar', this.fileToUpload, this.fileToUpload.name );
    this.userService.uploadDpImage(formData, this.currentUser).subscribe(
      (data:{Message:string, location:string})=>{
        this.userProfile.dpLocation=data.location;
      }
    )
  }

使用混合中间件的Nodejs路由:

router.post('/api/dpUpload/:displayName', middleWare.uploadToS3, (req,res)=>{
     User.findOneAndUpdate(
         {displayName: req.params.displayName},
         {$set:{dpLocation: req.file.Location}},
         (err,obj)=>{
             if(!err){
                return res.json({Message: "Image uploaded successfully", location:req.file.Location});
             }else{
                return res.json(err);
            }
         }
     )
})

多人中间件:

//S3 storage options
var multer = require('multer');
var s3Storage = require('multer-sharp-s3');
var aws = require('aws-sdk');
var fs = require('fs');
var nodeuuid = require('node-uuid');

aws.config.update({Bucket:'yaavarum-kelir-dev', region: 'us-east-2', accessKeyId: 'XXXXXXXXXXXX', secretAccessKey: 'XXXXXXXXXXXXX'});

s3 = new aws.S3();

var storage = s3Storage({
    s3,
    Bucket: 'yaavarum-kelir-dev',
    Key: `${'yaavarum-kelir-dev'}/DevContainer/${nodeuuid.v4()}`,
    ACL: 'public-read',
  });


middleWareObj.uploadToS3=multer({
    storage: storage,
}).single('avatar');

我面临的问题是,每次来电后,图像都会以相同的名称上传到AWS s3,因此将替换图像而不是创建新文件。我不确定自己做错了什么。

我每次通过在“存储”变量中执行“ nodeuuid.v4()”来生成新名称。但是,这个问题仍在发生。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我已解决此问题,感谢此答案:

https://stackoverflow.com/a/40950313/7999756

正确执行中间件:

middleWareObj.uploadToS3=multer({
    storage: s3Storage({
        s3,
        Bucket: 'yaavarum-kelir-dev',
        Key: function(req,file,cb){
            console.log(file);
            cb(null,nodeuuid.v4());
        },
        ACL: 'public-read',
      }),
}).single('avatar');