我正在尝试使用axios和express-fileupload上载图像,但是我不确定此处缺少的内容不起作用,控制台中的“找不到文件”,有时错误500。
这是我的代码:
<input type="file" name="file" class="hidden" ref="update_avatar_input" @change="update_avatar" accept="image/*">
<vs-button type="border" class="mr-4" @click="$refs.update_avatar_input.click()">Change Avatar</vs-button>
update_avatar (event) {
this.loading = true
const file = event.target.files || event.dataTransfer.files
if (!file.length) return
const formData = new FormData()
formData.set('file', event.target.files[0])
formData.set('id', this.data_local.id)
axios.post('http://localhost:8081/api/users/imgupload', formData, {
headers: {'Content-Type': 'multipart/form-data'}
}).then(response => {
if (response.data.error) {
console.log('error', response.data.error)
} else {
console.log('success', response.data.message)
this.avatar = `/server/uploads/${event.target.files[0].name}`
}
}).catch(error => {
console.log(error.response)
})
}
服务器端:
router.post('/imgupload', imgupload)
imgupload: (req, res) => {
if (!req.files) {
return res.status(500).send({ msg: 'file is not found' })
}
// accessing the file
const myFile = req.files.file
// mv() method places the file inside public directory
myFile.mv(`/server/uploads/${myFile.name}`, function (err) {
if (err) {
console.log(err)
return res.status(500).send({ msg: 'Error occured' })
}
// returing the response with file path and name
return res.send({name: myFile.name, path: `/${myFile.name}`})
})
}