admin管理员组

文章数量:1435859

Looking for some help in creating a React-js ponent to upload an image with preview and display the returned processed Image. API server return a binary png and not a url to the image. Resulting image should be displayed in a separate Div

Regards

I am not able to find a good example to upload image to a API server and display the returned binary image file

Looking for some help in creating a React-js ponent to upload an image with preview and display the returned processed Image. API server return a binary png and not a url to the image. Resulting image should be displayed in a separate Div

Regards

I am not able to find a good example to upload image to a API server and display the returned binary image file

Share Improve this question edited Nov 22, 2022 at 17:16 Vuely AI asked Nov 22, 2022 at 17:09 Vuely AIVuely AI 552 silver badges5 bronze badges 1
  • Please provide enough code so others can better understand or reproduce the problem. – Community Bot Commented Nov 22, 2022 at 18:50
Add a ment  | 

1 Answer 1

Reset to default 5

Use this code as a sample:

const MyComponent = () => {
    const [previewImage, setPreviewImage] = useState(null);
    const [uploadedImage, setUploadedImage] = useState(null);

    const handleUploadImage = () => {
        const data = new FormData();
        data.append('files[]', previewImage);

        fetch(/* server url */, { method: 'POST', body: data }).then(async (response) => {
            const imageResponse = await response.json();
            setUploadedImage(imageResponse);
        }).catch((err) => {

        });
    }

    const handleSelectImage = (event) => {
        const file = event.target.files[0];
        const fileReader = new FileReader();
        fileReader.addEventListener("load", () => {
            setPreviewImage(fileReader.result);
        });
        fileReader.readAsDataURL(file);
    }

    return (
        <div>
            <input type="file" onChange={handleSelectImage} />
            {
                previewImage ?
                    <img src={previewImage} alt="preview-image" />
                :
                    null
            }
            {
                uploadedImage ?
                    <img src={uploadedImage} alt="uploaded-image" />
                :
                    null
            }
            <button onClick={handleUploadImage}>Upload</button>
        </div>
    );
}

本文标签: javascriptReactjs How to upload Image with preview and display the processe imageStack Overflow