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

时间:2018-01-29 06:08:21

标签: javascript reactjs amazon-s3

我正在尝试将文件上传到aws s3。在我上传之前我想通过添加时间戳到文件名来重命名它。但我提出错误为'无法分配对象'#''的只读属性'名称'

这是代码

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;

enter image description here

3 个答案:

答案 0 :(得分:7)

是的,将它设置为只读听起来像一个奇怪的规则,但它是什么...... 因此,解决方法并非如此困难,就是从前一个创建一个新的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);




但请注意,如果您需要支持不支持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);
}




答案 1 :(得分:4)

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

答案 2 :(得分:2)

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);