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
1 Answer
Reset to default 5Use 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
版权声明:本文标题:javascript - React-js: How to upload Image with preview and display the processe image - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745673041a2669686.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论