Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 503
Michael Avatar asked Feb 12 '14 06:02

Michael


People also ask

How to change name of the file in JavaScript from input file?

Turns out we can't update the name property of a file. To rename a file we have to create a new file and pass our new name to the File constructor. const myRenamedFile = new File([myFile], 'my-file-final-1-really. txt'); console.

How do I change the filename in input type file?

To change the name of a File object, you need to create a new File instance. You can create one from a previous File object and it will act a simple wrapper over the data on disk. The sketchier part is to update the <input type="file"> value to use this new File.


2 Answers

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.

like image 107
Alexander Taborda Avatar answered Sep 21 '22 07:09

Alexander Taborda


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]'

like image 21
Terry Avatar answered Sep 21 '22 07:09

Terry