Multer S3 с узлом возвращает те же ключи - PullRequest
0 голосов
/ 23 февраля 2020

Я пытался решить это весь день сейчас, я не знаю, это только я испытываю это. не было никаких проблем вообще, и внезапно это подошло. каждый раз, когда я пытаюсь загрузить фотографии, я получаю один и тот же ключ для некоторых фотографий.

[0]   {
[0]     fieldname: 'image',
[0]     originalname: '00Q0Q_8bLxO6vGJ6_600x450.jpg',
[0]     encoding: '7bit',
[0]     mimetype: 'image/jpeg',
[0]     size: 23128,
[0]     bucket: 'lodos',
[0]     key: '1582459801328',
[0]     acl: 'public-read',
[0]     contentType: 'application/octet-stream',
[0]     contentDisposition: null,
[0]     storageClass: 'STANDARD',
[0]     serverSideEncryption: null,
[0]     metadata: { fieldName: 'image' },
[0]     location: 'https://lodos.s3.ap-southeast-2.amazonaws.com/1582459801328',
[0]     etag: '"c145b4ea1a0e8be4f581ae56268c7f24"',
[0]     versionId: undefined
[0]   },
[0]   {
[0]     fieldname: 'image',
[0]     originalname: '00202_bT8adcHePtb_600x450.jpg',
[0]     encoding: '7bit',
[0]     mimetype: 'image/jpeg',
[0]     size: 35577,
[0]     bucket: 'lodos',
[0]     key: '1582459801328',
[0]     acl: 'public-read',
[0]     contentType: 'application/octet-stream',
[0]     contentDisposition: null,
[0]     storageClass: 'STANDARD',
[0]     serverSideEncryption: null,
[0]     metadata: { fieldName: 'image' },
[0]     location: 'https://lodos.s3.ap-southeast-2.amazonaws.com/1582459801328',
[0]     etag: '"9300a33dcf76feb972e7b732953ac3e0"',
[0]     versionId: undefined
[0]   },

вот мой маршрут:

router.post('/forsale', (req, res) => {

    const multiple = upload.array('image', 6)

    multiple(req, res, function (err) {

        const { errors, isValid } = validateForSalePosts(req.body)

        const fileArray = req.files;


        if (err) {
            errors.image = 'File Upload Error'
            return res.status(400).json(errors)
        }



        if (!isValid) {
            for (let i = 0; i < fileArray.length; i++) {
                s3.deleteObjects({
                    Bucket: 'lodos',
                    Delete: {
                        Objects: [{
                            Key: fileArray[i].key
                        }]
                    }

                }, function (err, data) {
                    if (err) console.log(err);
                    else console.log(data);
                })
            }
            return res.status(400).json(errors)
        }


        const newForSalePost = new ForSalePosts({
            title: req.body.title,
            description: req.body.description,
            name: req.body.postedby,
            price: req.body.price,
            make: req.body.make,
            model: req.body.model,
            language: req.body.language,
            condition: req.body.condition,
            email: req.body.email,
            phonenumber: req.body.phonenumber,
            town: req.body.town,
            city: req.body.city,
            state: req.body.state,
            user: req.body.userid,
            category: req.body.category,
            odometer: req.body.odometer,
            subcategory: req.body.subcategory

        })

        if (fileArray.length !== 0) {
            const listoflinks = [];

            for (let i = 0; i < fileArray.length; i++) {

                const link = fileArray[i].location
                listoflinks.push(link)
            }

            for (var i = 0; i < listoflinks.length; i++) {
                newForSalePost.links.push(listoflinks[i])
            }
        }



        newForSalePost.save().then(post => {

            AllPosts.updateOne({ user: post.user },
                {
                    $push: {
                        posts: {
                            postid: post._id,
                            title: post.title,
                            category: post.category,
                            subcategory: post.subcategory,
                        }
                    }
                }, (err) =>
                res.json(post))
        }).catch(err => console.log(err))
    })
})


aws.config.update({
    secretAccessKey: keys.secretAccessKey,
    accessKeyId: keys.accessKeyId,
    region: 'ap-southeast-2'
})
const s3 = new aws.S3();


const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/gif') {
        cb(null, true)
    }
    else {
        cb(new Error('Invalid Type'), false)
    }
}

const size = (req, file, cb) => {
    if (file.size < 5000000) {
        cb(null, true)
    }
    else {
        cb(new Error('Max File Size 5 MB'), false)
    }
}


const upload = multer({
    fileFilter: fileFilter,
    size: size,
    storage: multerS3({
        s3: s3,
        bucket: 'lodos',
        acl: 'public-read',
        metadata: function (req, file, cb) {
            cb(null, { fieldName: file.fieldname })
        },
        key: function (req, file, cb) {
            cb(null, Date.now().toString())
        }
    })
})

Буду признателен за любую помощь. это просто создает ненужные файлы в моем ведре, кроме того, что я не являюсь тем, что мне нужно во внешнем интерфейсе.

вот как я ловлю его во внешнем интерфейсе:

 data.append('image', this.state.selectedFile);
...