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

Pra*_*k N 6 javascript amazon-s3 reactjs

我正在尝试将文件上传到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;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Kai*_*ido 10

是的,这听起来像一个奇怪的规则,将它设置为只读,但它就是它...所以解决方法,不是那么难,是从你以前的一个创建一个新的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);
Run Code Online (Sandbox Code Playgroud)

但另请注意,如果您需要支持不支持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);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@Kaiido.为s3 params设置关键变量对我来说很有用.如果不使用aws s3,您的解决方案可能会有所帮助. (2认同)

小智 9

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);
Run Code Online (Sandbox Code Playgroud)

  • 简单干净。 (2认同)

Ale*_*lin 7

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