简体   繁体   English

JavaScript 无法在上传前重命名文件

[英]JavaScript not able to rename file before upload

I am trying to upload file to aws s3.我正在尝试将文件上传到 aws s3。 before i upload i want to rename it by adding timestamp to file name.在我上传之前,我想通过在文件名中添加时间戳来重命名它。 but i am geting an error as 'Cannot assign to read only property 'name' of object '#''但我收到一个错误,因为“无法分配给只读属性“名称”的对象“#”

here is the code这是代码

let file = e.target.files[0];
let timeStamp = (new Date()).getTime();
let fileExt = file.name.split('.')[file.name.split('.').length-1];
let fileNameWithoutExt = file.name.replace(`.${fileExt}`,'');
let newFileName = fileNameWithoutExt + '_' + timeStamp + '.' + fileExt;
file.name = newFileName;

在此处输入图片说明

Yep that sounds like a weird rule to set it as Read-only, but it's what it is... So the workaround, not so hard, is to create a new File object from your previous one...是的,将它设置为只读听起来像是一个奇怪的规则,但它就是这样......所以解决方法,不是那么难,是从你以前的对象创建一个新的 File 对象......

 var previous_file = new File(['foo'], 'file.txt', {type: 'text/plain'}); try{ previous_file.name = 'hello.txt'; } catch(e){} console.log(previous_file.name); // didn't work // so we just create a new File from it... var new_file = new File([previous_file], 'hello.txt'); console.log(new_file);

But also note that if you need to support older browsers that don't support the File constructor, then you can override this file name in a FormData that you will send to your sever:但还要注意,如果您需要支持不支持 File 构造函数的旧浏览器,那么您可以在将发送到服务器的 FormData 中覆盖此文件名:

 var file = new File(['foo'], 'text.txt', {type:'text/plain'}); var formdata = new FormData(); // this will override the file name formdata.append('file', file, 'hello.txt'); // and now you can send this formdata through xhr // for demo, we will just log its content for(let entry of formdata.entries()) { console.log(entry); }

The append() method of FormData accepts a third optional filename parameter. FormData 的 append() 方法接受第三个可选文件名参数。

// new file name as a variable with timestamp
const newName = new Date().getTime() + event.target.files[0].name;  
fd.append('file[]', event.target.files[0], newName);

instead of key = "folder1/folder2/${filename}" you can write key = "folder1/folder2/youfilename.txt"而不是key = "folder1/folder2/${filename}"你可以写key = "folder1/folder2/youfilename.txt"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM