I am using a library react-avatar-editor for creating profile picture of the user. Below is the code which I am using the send the cropped image to the server
const canvasScaled = this.editor.getImageScaledToCanvas(); //a canvas object
canvasScaled.toBlob((blob) => {
this.setState({
preview: blob
},
() => {
let data = new FormData();
const file = new File([blob], "my-image", {
type: "image/png"
});
data.append("file", file);
axios({
method: "POST",
data: data,
url: "/media",
headers: {
'Content-Type': 'multipart/form-data'
}
}).then().catch()
}
);
})
But the image generated at the server is a black image. Tested with many files but result is same - a black image.
My backend service is written in JAVA so I tested if the backend service handling the image correctly or not, I wrote a simple file selected
<input type="file" accept={"image/png"} onChange={onSelect}/>
<button onClick={() => {
const data = new FormData();
data.append("file", this.state.file);
axios({
method: "POST",
data: data,
url: "/media",
headers: {
'Content-Type': 'multipart/form-data'
}
}).then().catch()
}}>Send<button>
And yes, the service side code is working fine with above POST
request. Which means, I have definitely something wrong written at the react-avatar-editor handling code.
Is it the blob
causing the issue? How the image is sent in the case of a file-selector? Base64 or blob?
Update: I noticed a strange behavior with an image. If I upload this file This gets converted to which is not a complete black image. Something fishy is going on with colors.
To check if the library itself is creating the black image, I check it using canvasScaled.toDataURL("image/png")
and used this into an image, and yes there is no issue with the created canvas, image is getting rendered.
Try data.append("file", blob);
without calling new File
. According to MDN,
A File object is a specific kind of a Blob, and can be used in any context that a Blob can. In particular, FileReader, URL.createObjectURL(), createImageBitmap(), and XMLHttpRequest.send() accept both Blobs and Files.
add this in second line after defining canvasScaled
var ctx = canvasScaled.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.