Reputation: 577
I am trying to resize an uploaded image and then upload the new image. My code runs without error and I could see the image was resized successfully but somehow the original image is being uploaded instead of the newly created image.
I am guessing e.target.files[0] = newimg; is not the right way to change the uploaded image file to the new image file. What should be the correct way?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ResizeImg(e)
{
const file = e.target.files[0];
const fileName = file.name;
const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = event =>
{
const img = new Image();
img.src = event.target.result;
img.onload = () =>
{
const elem = document.createElement('canvas');
const ctx = elem.getContext('2d');
const maxWidth = 50;
const maxHeight = 50;
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height);
const width = img.width * ratio + .5 | 0;
const height = img.height * ratio + .5 | 0;
elem.width = width;
elem.height = height;
ctx.drawImage(img, 0, 0, width, height);
ctx.canvas.toBlob((blob) =>
{
const newimg = new File([blob], fileName, file);
e.target.files[0] = newimg;
});
}
};
}
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input name="infile" type="file" onchange="ResizeImg(this)">
<br><br><input type="submit" name="submit">
</form>
</body>
</html>
Upvotes: 0
Views: 1226
Reputation: 577
Found the answer at Resize image in the client side before upload. File input's filelist can be change with fileInput.files = fileList
Upvotes: 0
Reputation: 261
You are doing it technically correct BUT files from input are read only. So browser will not let you change those files. What you can do is create new form data and append all new images inside that and send upload it using fetch to send it async without refreshing page.
Upvotes: 1