【发布时间】:2022-01-20 14:31:06
【问题描述】:
我有一个反应项目,我正在尝试让照片上传和存储工作。我目前有一个表单,用户可以在其中上传个人资料图片。上传头像后,整个文件对象会随着来自 react 前端的 axios 请求一起发送到 sequelize 后端。我遇到了在请求正文中发送整个文件对象的问题,但是当我在控制器中 console.log 时......它显示的是一个空对象而不是我知道我从前端发送的文件对象到后端。
我不知道为什么所有数据都丢失了。
这里是发送 axios 请求的 react 函数:
function createProfile(userId){
console.log('about to create profile with picture')
console.log(profilePicture)
axios.post('/api/profile/', {
'profile_pic':profilePicture,
'f_name':firstName,
'l_name':lastName,
'bio':bio,
'location':location,
'sm_facebook':facebook,
'sm_instagram':instagram,
'sm_twitter':twitter,
'sm_website':website,
'followers':0,
'following':0,
'photos':0,
'edits':0,
'downloads':0,
'userId':userId
})
.then((data) => {
return(<Navigate to='/' />)
})
.catch((err) => {
console.error(err)
})
}
console.log(profilePicture) 显示以下内容:
File {name: 'pexels-any-lane-5946095.jpg', lastModified: 1638937909688, lastModifiedDate: Tue Dec 07 2021 20:31:49 GMT-0800 (Pacific Standard Time), webkitRelativePath: '', size: 504333, …}
lastModified: 1638937909688
lastModifiedDate: Tue Dec 07 2021 20:31:49 GMT-0800 (Pacific Standard Time) {}
name: "pexels-any-lane-5946095.jpg"
size: 504333
type: "image/jpeg"
webkitRelativePath: ""
[[Prototype]]: File
这是后端控制器:
post:(req, res) => {
const dirPath = '/Users/omarjandali/dev/fotos-web/backend/client/static/images/ProfilePictures'
console.log(__dirname)
console.log(req.body)
let body = req.body
Profile.create({
profile_pic: "diller",
f_name: body.f_name,
l_name: body.l_name,
bio: body.bio,
location: body.location,
sm_facebook: body.sm_facebook,
sm_instagram: body.sm_instagram,
sm_twitter: body.sm_twitter,
sm_website: body.sm_website,
followers: body.followers,
following: body.following,
photos: body.photos,
downloads: body.downloads,
edits: body.edits,
userId: body.userId
})
.then((data) => {
res.send(data).status(200)
})
.catch((err) => {
console.error(err)
res.send(err).status(400)
})
},
console.log(req.body) 显示以下对象:
{
profile_pic: {},
f_name: 'assad',
l_name: 'jandali',
bio: 'bio',
location: 'location',
sm_facebook: 'https://facebook.com',
sm_instagram: 'https://instagram.com',
sm_twitter: 'https://twitter.com',
sm_website: 'http://omarjandali.com',
followers: 0,
following: 0,
photos: 0,
edits: 0,
downloads: 0,
userId: 4
}
如您所见,个人资料图片并未通过请求一直发送。
【问题讨论】:
-
我建议您添加一个带有此处建议的数据类型的标题:stackoverflow.com/questions/39663961/…
-
你好@Cmontalvo80 我看到你回答了一个与此类似的问题,但由于某种原因该解决方案不起作用。你能帮我解决这个问题吗? react-file-base64 似乎没有成功
标签: javascript reactjs axios sequelize.js