我已经被困了好几天了。 在 Nuxt3 中,我将使用 multer S3 作为表单数据将图像上传到 aws bucket。
然而,下面的代码中并没有任何操作。 你能告诉我我错过了什么吗?
useFetch 不熟悉。 在axios的例子中,转入没有问题
const url = await this.$axios.post('/api/upload', form)
但是 Nuxt3 获取很困难。
提前感谢您的帮助。
客户端.vue
const handleFileChange = async () => {
let formdata = new FormData()
const getImg = image.value.files[0]
formdata.append('image', image.value.files[0])
try {
const res = await useFetch('/api/imgUploader', {
method: 'POST',
body: formdata
})
fileName.value = getImg.name
const result = res.data._rawValue
console.log(result)
} catch (e) {
console.log(e)
}
}
imgUploader.ts
import { uploadToStorage } from "../api/upload"
export default defineEventHandler(async (event) => {
if(event.node.req.method == 'POST'){
console.warn('req uploader apis')
try {
console.warn('upload')
uploadToStorage.single('image'), (res: any, req:any) => {
try {
res.status(200).json({ result: 'ok' })
} catch (error) {
console.warn(error)
}
}
} catch (e) {
console.warn(e)
}
}
})
上传.ts
import multer from 'multer'
import multerS3 from 'multer-s3'
import shortId from 'shortid'
import { S3Client } from '@aws-sdk/client-s3'
const uploadToStorage = multer({
storage: multerS3({
s3: new S3Client({
credentials: {
accessKeyId: 'my-accessKeyId',
secretAccessKey: 'my-secretAccessKey',
},
endpoint: {
hostname: 'my-hostname',
protocol: 'http',
path: '/',
},
region: 'my-region',
}),
bucket: 'my-bucket',
acl: 'public-read',
contentType: multerS3.AUTO_CONTENT_TYPE,
cacheControl: 'max-age=31536000',
key: function (req, file, cb) {
const fileId = shortId.generate();
const type = file.mimetype.split('/')[1];
const fileName = `${fileId}.${type}`;
cb(null, fileName);
},
})
})
export { uploadToStorage }