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

后端 未结 3 964
情深已故
情深已故 2021-02-01 19:29

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 htm

相关标签:
3条回答
  • 2021-02-01 20:13

    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.

    0 讨论(0)
  • 2021-02-01 20:22

    From reading https://developer.mozilla.org/en-US/docs/Web/API/File/File#Syntax the bits parameter of the File constructor can be an array of Blob objects.

    bits

    An Array of ArrayBuffer, ArrayBufferView, Blob, USVString objects, or a mix of any of such objects, that will be put inside the File. USVString objects are encoded as UTF-8.

    From reading https://developer.mozilla.org/en-US/docs/Web/API/File#Methods it turns out the File inherits from Blob:

    The File interface doesn't define any methods, but inherits methods from the Blob interface

    Therefore, new File([originalFile]) is valid.

    I came up with the following which works for me:

    function renameFile(originalFile, newName) {
        return new File([originalFile], newName, {
            type: originalFile.type,
            lastModified: originalFile.lastModified,
        });
    }
    
    0 讨论(0)
  • 2021-02-01 20:33

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

    0 讨论(0)
提交回复
热议问题