How to create a modified copy of a File object in JavaScript?(如何在 JavaScript 中创建文件对象的修改副本?)
问题描述
从 <input type="file">
接收的文件的属性是只读的.
Properties of files received from an <input type="file">
are read-only.
例如,以下重写 file.name
的尝试要么静默失败,要么抛出 TypeError: Cannot assign to read only property 'name' of object '#<File>'代码>.
For example, the following attempt to re-write file.name
would either fail silently or throw TypeError: Cannot assign to read only property 'name' of object '#<File>'
.
<input onchange="onchange" type="file">
onchange = (event) => {
const file = event.target.files[0];
file.name = 'foo';
}
尝试通过 Object.assign({}, file)
创建副本失败(创建一个空对象).
Attempting to create a copy via Object.assign({}, file)
fails (creates an empty object).
那么如何克隆一个 File
对象呢?
So how does one clone a File
object?
推荐答案
我的解决方案在于 File
构造函数:
My solution lay in the File
constructor:
https://developer.mozilla.org/en-US/docs/Web/API/File#Implementation_notes
它本身就是Blob
的扩展:
https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
let file = event.target.files[0];
if (this.props.distro) {
const name = 'new-name-here' + // Concat with file extension.
file.name.substring(file.name.lastIndexOf('.'));
// Instantiate copy of file, giving it new name.
file = new File([file], name, { type: file.type });
}
注意 File()
的第一个参数必须是一个数组,而不仅仅是原始文件.
Note the first argument to File()
must be an array, not simply the original file.
这篇关于如何在 JavaScript 中创建文件对象的修改副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 中创建文件对象的修改副本?


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01