How to change name of file in javascript from inpu

2020-02-26 06:38发布

问题:

I need to change the filename (not the file, just the metadata of the name) when uploading to a sharepoint site.

I figured that it would be easy enough to change the html attribute in javascript rather than playing with Sharepoint backend. So that when I upload a file it changes the name of the file (not the data)

something like this:

function PreSaveAction(){
   var file = document.GetElementById('fileupload1');
   file.files[0].name='ChangedName.tmp'

return true;
}

Is this impossible due to the nature of the locked input='file' attributes?

回答1:

try this:

var element = document.GetElementById('fileupload1');
var file = element.files[0];
var blob = file.slice(0, file.size, 'image/png'); 
newFile = new File([blob], 'name.png', {type: 'image/png'});

note: this is for a image type, you have to change this type with type you're actually using.



回答2:

A simpler and more memory efficient approach - change the file's 'name' property to writeable:

Object.defineProperty(fileToAmend, 'name', {
  writable: true,
  value: updatedFileName
});

Where fileToAmend is the File and updatedFileName is the new filename.

Method from Cannot assign to read only property 'name' of object '[object Object]'