【发布时间】:2022-02-09 19:21:53
【问题描述】:
首先JS不是我常用的语言,如果问题不是很清楚,请见谅。
我一直在测试用于压缩用户上传到<input> 的图像的代码,压缩的 JS 代码运行良好,但我不知道如何替换他们在“输入”中选择的文件" 由我刚刚生成的压缩文件。
我想这样做是因为<input> 在表单中,因此我可以将图像压缩上传到服务器。
这里是 JS fot 压缩:
const MAX_WIDTH = 300;
const MAX_HEIGHT = 200;
const MIME_TYPE = "image/jpeg";
const QUALITY = 0.8;
const input = document.getElementById("img-1");
input.onchange = function (ev) {
const file = ev.target.files[0]; // get the file
const blobURL = URL.createObjectURL(file);
const img = new Image();
img.src = blobURL;
img.onerror = function () {
URL.revokeObjectURL(this.src);
// Handle the failure properly
console.log("Cannot load image");
};
img.onload = function () {
URL.revokeObjectURL(this.src);
const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
const canvas = document.createElement("canvas");
canvas.width = newWidth;
canvas.height = newHeight;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, newWidth, newHeight);
canvas.toBlob(
blob => {
// Do something with img in my case show in Frontend
displayInfo('Original file', file);
displayInfo('Compressed file', blob);
},
MIME_TYPE,
QUALITY);
// Only for testing and see results
document.getElementById("pruebas-tam").append(canvas);
};
};
【问题讨论】:
-
您的
<input>是<input type='file'吗? (暗示是这样)出于浏览器安全原因,您不能更改type='file'值。 -
没错,我读过,但我不想选择文件,我只想将他上传的文件更改为相同但压缩的文件。
-
您可以在提交中重建表单数据,以便您上传新文件数据而不是输入中的文件。见developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
-
@Twisty 这似乎是一个可行的选择,但令我惊讶的是,一个必须相当普遍的问题没有标准解决方案。我会试试你的推荐,谢谢!
标签: javascript html jquery