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 中创建文件对象的修改副本?
 
				
         
 
            
        基础教程推荐
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				