javascript - 无法使用反应上传图像并保存到文件夹
问题描述
我正在尝试在 react 中上传图像,我使用了扩展名 ** react-image-upload **。我使用此代码在网页上显示图像
import React from 'react';
import ImageUploader from 'react-images-upload';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { pictures: [] };
this.onDrop = this.onDrop.bind(this);
}
onDrop(pictureFiles, pictureDataURLs) {
this.setState({
pictures: pictureFiles
});
}
render() {
return (
<ImageUploader
withIcon={true}
buttonText='Choose images'
onChange={this.onDrop}
imgExtension={['.jpg', '.gif', '.png', '.gif']}
maxFileSize={5242880}
/>
);
}
}
现在图像显示在网页上,但我不知道如何上传并将其保存到我尝试使用此代码的文件夹中。
- 此行用于 onChange
onDrop(pictureFiles, pictureDataURLs) {
this.setState({
picture: pictureFiles
});
}
- 此行正在上传图像,但我不知道它将如何工作以及是否需要添加后端。
uploadHandler = () => {
const formData = new FormData();
formData.append('file', this.state.picture);
console.log()
let context = 'profile';
service.uploadImage(formData,
this.state.picture,
context, (res) => {
if (res.status === "ERROR") {
console.log("ERROR: ", res);
stopLoading();
}
});
}
还有上传功能——
export const uploadImage = (file, fileName, context, onDone) => {
console.log(fileName)
post(encodeURI("/api/upload-files/" + fileName + "/" + context), file, (res) => {
onDone(res.data);
});
};
而后端代码,我正在使用 FastAPI- Python 来实现它-
@router.post("/upload-files")
async def image(image: UploadFile = File(...)):
print(image.filename)
return {"filename": image.filename}
我检查了值,结果在后端正确,但在网页上显示 422:预处理错误。请给出一些想法是什么过程或一些提示,以便我可以完成代码。
解决方案
推荐阅读
- scala - scala混合视图和表达式中的严格集合
- python - 使用 Python 代码将数据从 JSON 文件导入 mysql
- javascript - 未捕获的类型错误:无法设置未定义的属性“背景”。将样式放在课堂上
- apache-kafka - Kafka Streams:带配置参数的 DeserializationExceptionHandler
- php - 使用 PHP + AJAX 从两个 MySQL 表中同时获取数据
- python-3.x - Keras:文本摘要的注意力机制
- r - 在函数内使用嵌套变量
- ionic-framework - 打包成 APK 时,cordova-plugin-bluetoothle 无法发现设备
- ruby-on-rails - 找不到 'id'=1
- javascript - async await 内部如何工作?