[英]How to upload 2 image different 2 folder with NodeJs Multer?
我遇到問題並堅持如何使用 NodeJs Multer 上傳 2 個圖像不同的 2 個文件夾? 我使用 s3 AWS 服務將我的圖像上傳到存儲桶
我的路線代碼:
const { s3Service } = require('../../services')
module.exports = (req, res, next) => {
const controller = new Controller()
const router = new express.Router()
router.route('/createEvent').post(
s3Service.upload.single('image'),
controller.createEvent
)
我的多重代碼:
const multer = require('multer')
const AWS = require('aws-sdk')
const fs = require('fs')
const s3 = new AWS.S3({
accessKeyId: process.env.BUCKET_ACCESSKEYID,
secretAccessKey: process.env.BUCKET_SECRETACCESSKEY,
endpoint: process.env.BUCKET_ENDPOINT
})
const storage = multer.diskStorage({
filename: function (req, file, cb) {
let filename = file.originalname
filename = filename.replace(/ /g, '-')
cb(null, 'event' + '-' + Date.now() + '-' + filename)
}
})
const upload = multer({
storage
})
const uploadToBucket = (fileContent, folderName, fileName, fileType) => {
const params = {
Bucket: process.env.BUCKET_NAME,
Key: folderName + '/' + fileName,
Body: fs.createReadStream(fileContent),
ContentType: fileType,
ACL: 'public-read'
}
s3.upload(params, (err, data) => {
if (err) {
console.log(err)
}
if (data) {
fs.unlinkSync(fileContent)
const url = data.Location
console.log(url)
return url
}
})
}
我的控制器創建函數:
const path = req.file.path
s3Service.uploadToBucket(path, 'events', req.file.filename, req.file.mimetype)
payload.image = {
name: req.file.filename,
url: process.env.BUCKET_EVENTSTORAGE + req.file.filename,
type: req.file.mimetype,
size: req.file.size
}
const data = await Event.create(payload)
我已經上傳了 1 張圖片,但只有當 eventCertified 的值為true時,我才需要上傳另一張名為certificate的圖片。 我卡住了,以前從未嘗試過。
使用 multer,通常只需更改即可處理多個文件
從
const upload = multer({
storage
})
到
const max_files_limit=2 // whatever that meets your need
const upload = multer({storage}).array('images',max_files_limit); // 'images', the first parameter, should be the name of your fields in the HTML form,etc
// In your code it should be like this I suppose
s3Service.upload.array('images',max_files_limit)
在 multer 中間件上傳你的文件后,req 對象將具有 files 屬性。
您可以像那樣訪問多個文件
const files = req.files // simply use req.files to retreive all your files
const events_promises=[]
for(let i=0;i<req.files.length;i++){
s3Service.uploadToBucket(files[i].path, 'events', files[i].filename, files[i].mimetype)
payload.image = {
name: files[i].filename,
url: process.env.BUCKET_EVENTSTORAGE + files[i].filename,
type: files[i].mimetype,
size: files[i].size
}
events.push(Event.create(payload)) // put all your promises / async in an array
}
let events_result=Promise.all(events); // wait for all your promises to finish at once
await events_result // or events_result.then("something else");
我試圖遵循您的代碼邏輯,但我沒有對其進行測試或模擬,如果有錯字或意外錯誤,我們深表歉意。 在我的示例中,我將所有承諾 Event.create() 放在一個數組中,一次等待所有承諾,如果一個事件創建失敗,示例中的代碼將無法正確捕獲它。
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.