首页 > 解决方案 > 无法使用反应上传图像并保存到文件夹

问题描述

我正在尝试在 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}
            />
        );
    }
}

现在图像显示在网页上,但我不知道如何上传并将其保存到我尝试使用此代码的文件夹中。

  1. 此行用于 onChange
   onDrop(pictureFiles, pictureDataURLs) {
        this.setState({
            picture: pictureFiles
        });
    }
  1. 此行正在上传图像,但我不知道它将如何工作以及是否需要添加后端。
    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:预处理错误。请给出一些想法是什么过程或一些提示,以便我可以完成代码。

标签: javascriptreactjspython-3.x

解决方案


推荐阅读