javascript - 上传带有其他信息的图像文件(文本)
问题描述
我正在创建可以一起发布一些信息和图像文件的应用程序。我想我在后端成功了,但我不知道如何在前端使用 React。
后端我使用 node.js + multer + mongoDB .. 前端我使用 react.js + ajax ...
当我使用邮递员进行测试时,我未选中标题,并在正文中使用了表单数据并且它起作用了。
我已经尝试过的前端...
class CreateContainer extends Component {
constructor(){
super()
this.state = {
house : {
street: '',
address: '',
state: '',
zipcode: '',
year: '',
sqft: '',
productImage: ''
},
}
}
handleInput = (e) => {
const updatedChange = {
...this.state.house
}
updatedChange[e.target.name] = e.target.value;
this.setState({
house: updatedChange
})
}
handleSubmit = (e) => {
e.preventDefault();
const updatedHouse = {
...this.state.house
}
this.addHouse(updatedHouse)
this.setState({
house : {
street: '',
address: '',
state: '',
zipcode: '',
year: '',
sqft: '',
productImage: ''
}
})
}
addHouse = async(updatedHouse) => {
try{
const response = await fetch(`${process.env.REACT_APP_API}/api/v1/house`, {
method: 'POST',
credentials: 'include',
body: JSON.stringify(updatedHouse),
headers: {
'Content-Type' : 'application/json',
'Accept': 'application/json',
}
});
if(!response.ok){
throw Error(response.statusText)
}
const parsedCreateHouse = await response.json();
this.props.history.push('/home');
} catch(err) {
console.log('cannot make house');
}
}
后端
router.post('/', upload.single('productImage'), (req, res, next) => {
const userId = req.session.userId
const product = new House({
_id: new mongoose.Types.ObjectId(),
street: req.body.street,
address: req.body.address,
state: req.body.state,
zipcode: req.body.zipcode,
year: req.body.year,
sqft: req.body.sqft,
productImage: req.file.path,
userId: userId
});
product
.save()
.then(result => {
res.status(201).json({
message: 'handle post route',
createdProduct: {
_id: result._id,
street: result.street,
address: result.address,
state: result.state,
zipcode: result.zipcode,
year: result.year,
sqft: result.sqft,
request: {
type: 'GET',
url: 'http://localhost:9000/api/v1/house/' + result._id
}
}
});
})
.catch(err => {
console.log('error: post request fail');
res.status(500).json({
error: err
})
});
})
我想像这样创建和存储房屋信息和图片作为一个数据(?),...
{
"status": 200,
"data": {
"_id": "5d388b0cd8129405f01ba3da",
"address": "jjj",
"state": "jjj",
"zipcode": "jjj",
"year": "jjj",
"sqft": "jjj",
"productImage": "public/uploads/2019-07-24T16:45:00.501Zaudrey.png",
"__v": 0
}
}
解决方案
推荐阅读
- mysql - 如何使用通配符有效过滤 MySQL 中的分层数据?
- ios - 在 IOS 上设置 Firebase Crashlytics
- reactjs - 有人在 Typescript 中成功使用过 react-awesome-button 吗?
- r - R - for 循环中的 If-else 语句一次填充整个列,而不是该列中的每个索引
- reactjs - 屏幕阅读器支持反应组件
- rust - 无法打开创世配置文件
- c# - Unity IOException:在 output_log.txt 的路径上共享冲突,如何读取正在使用的文件?
- python - 使模型的第一个实例在 SQLAlchemy 中具有唯一字段
- swift - SWIFTUI Firebase 检索子集合数据
- qt - 是否在 deleteLater() 之前调用了所有 Qt 插槽?