【发布时间】:2021-10-02 03:33:36
【问题描述】:
我尝试将图像从客户端(在 react 中制作)发送到服务器(在 nodeJs 中制作),以便稍后将其上传到谷歌云存储。
但是 - 当我收到服务器 req.file 上的调用时,它是未定义的。 (我确实有 req.files.file 但我使用 multer 我应该定义 req.file。)
我将发布代码:
前面:
<input
accept='image/*'
className='ProfilePage__uploadImage'
onChange={onFileUploadChange()}
ref={inputFile}
name='file'
id='file'
type='file'
/>
onFileUploadChange 函数:
const onFileUploadChange = () => (event: React.ChangeEvent<HTMLInputElement>) => {
const image = event?.target?.files?.[0]
if (image !== undefined) {
const data = new FormData()
data.append('file', image)
axios.post('http://localhost:3006/users/uploadProfileImage', data, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
}
Node.js 服务器:
const multer = Multer({
storage: Multer.MemoryStorage,
limits: {
fileSize: 1000000, // Maximum file size is 10MB
}
})
usersRouter.post(
'/uploadProfileImage',
multer.single('file'),
(req, res, next) => {
// here it crushes - cannot read originalname of undefined.
const newFileName = req.file.originalname
const blob = bucket.file(newFileName)
const blobStream = blob.createWriteStream()
blobStream.on('error', (err) => console.log(err))
blobStream.on('finish', () => {
console.log('done')
})
blobStream.end(req.file.buffer)
})
【问题讨论】:
-
req.file.originalname,你必须在这里调试。文件必须在数组中所以你需要这样使用,,, req.file[0].originalfile // 可能是 req.files[0].originalfile ,, 你必须调试然后你很容易得到
-
事件?.target?.files?.[0] // 在反应方面,这将是 event?.target?.files[0]
标签: node.js reactjs axios multer