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?
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.
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.
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.
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]'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With