js 将一个图像输入值分配给另一个

js assign one image input value to another

我有两个图像输入字段

<input type="file" accept="image/*" id="one" />
<input type="file" accept="image/*" id="two" />

我正在尝试将值从 two 同步到 one,只要 two 收到输入,就将值分配给 onetwo只是前端可见的一个字段,one是用于数据收集和上传的原始表单。

two.onchange = () => {one.value = two.value}

既然是文件字段,不知道会不会行得通(还没写单元测试,因为即使是前面记录的值,我怀疑文件会不会被后端抓到)。如果有人提出切实可行的方法,我将不胜感激。

你做错了你必须设置 .files 属性 而不是 .value 因为浏览器将文件存储在 files 属性 而不是 value 属性。您可以像下面那样做 示例:

const one = document.getElementById('one');
const two = document.getElementById('two');
two.onchange = () => {one.files = two.files}
<input type="file" accept="image/*" id="one" />
<input type="file" accept="image/*" id="two" />

抱歉,@Abdul Basit 的回答无效。我试图分配 files 但结果在前端工作,但实际上没有数据传输到后端。因此,不可能在文件输入之间分配值(文件)

one.files = two.files
<MultiValueDict: {}>

我是通过DOM替换完成的。

// replace image input
two.remove();
Array.from(one.attributes).forEach(attr => {
    two.setAttribute(attr.nodeName, attr.nodeValue);
});
one.parentNode.replaceChild(two, one);
<MultiValueDict: {'image': [<InMemoryUploadedFile: main.jpg (image/jpeg)>]}>

这里我们最终在后端获得了文件。