我想做以下事情:
1. Setup a Form where a user can upload images/text
2. Send form data over to express server via POST API
3. Receive form data in express and upload to cloudinary
4. Get cloudinary callback with url for image
5. Save rest of form data + cloudinary_image_url to database
我已完成第1步:
render(){
return (
<form onSubmit={this.handleCreate.bind(this)}>
<input type="text" placeholder="Location" ref="location"/>
<textarea placeholder="Description" ref="description"/>
<input type="file" ref="image"/>
<button>Add</button>
{this.renderError()}
</form>
)
}
handleCreate(event){
event.preventDefault();
const location = this.refs.location;
const description = this.refs.description;
const image = this.refs.image;
const validateInput = this.validateInput(location.value, description.value, image.value);
if (validateInput) {
this.setState({error: validateInput});
return;
}
this.setState({error:null});
this.props.createMemory(location.value, description.value, image.files[0]);
}
基本上,我使用React Flux来处理api调用。按下add
按钮后,我的代码将触发createMemory
函数,该函数将触发将调用API函数的操作:
export function createMemory(location, description, image) {
axios.post('http://localhost:3000/uploads', {
location,
description,
image
}).then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
现在可以轻松传递location
和description
,但我无法传递图像。我知道我需要使用某种多数据库(如multer
)来处理图像。
现在我的后端快递服务器上有:
var upload = multer({dest:&#39; uploads /&#39;});
app.post('/upload', upload.single('image'), async (req, res) => {
try {
console.log(req.file);
} catch (err) {
res.sendStatus(400);
}
})
现在我应该req.file
成为image
文件,但我得到undefined...
。我知道这是一个很长的问题,但我做错了什么?