How to change name of file in javascript from input=File

michael picture michael · Feb 12, 2014 · Viewed 25k times · Source

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?

Answer

Alexander Taborda picture Alexander Taborda · Sep 20, 2017

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.