上传到Amazon S3后从本地存储删除图像

时间:2019-04-15 17:45:46

标签: node.js amazon-web-services amazon-s3 multer

我正在使用TinyPNG压缩在表单中上传的图像,然后存储在Amazon s3云存储中。压缩完成并在线保存到存储桶后,我已经保存了一个uploads文件夹,用于临时存储和删除图像。

index.js

const storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, './uploads');
    },
    filename: function(req, file, cb){
        cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname);
    }
});

const fileFilter = (req, file, cb)=>{
    if(file.mimetype.match(/jpeg|jpe|png|jpg$i/)){
        cb(null, true);
    }else {
        cb(new Error("Only JPG and PNG files allowed"), false);
    }
};

const tinify = require("tinify");
tinify.key = "abc";

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 14
    },
    fileFilter: fileFilter
});

let cpUpload = upload.fields(
    [
        { name: 'img1', maxCount: 1 },
        { name: 'img2', maxCount: 1 }
    ]
);

router.post('/uploadForm', cpUpload, function(req, res, next) {
    const source = tinify.fromFile(req.files['img'][0].path);
    source.store({
        service: "s3",
        aws_access_key_id: "xyz",
        aws_secret_access_key: "abc",
        region: "us-west-1",
        headers: {
            'Cache-Control': "public, max-age=31536000"
        },
        path: "testbucket/"+req.files['img'][0].filename
    });
    let path = req.files['img'][0].path;
    fs.unlink(path, (err)=>{
        if(err) throw err;
        console.log('successfully deleted file');
    });
}

但是,在完成压缩之前,文件已从uploads文件夹中删除。我该如何克服?

0 个答案:

没有答案