Home > Software design >  How to add an id property to a File?
How to add an id property to a File?

Time:03-19

I have an input to upload files. The uploaded files are shown as list displaying the file.name. When I add an id-property to a file it loses all it's properties except the path property. How can I add an id properly?

const fileWithId = {...uploadedFile, id: "myIdName"}  //does not work

CodePudding user response:

You can't copy File objects, they're largely-opaque data structures other than the specified properties, which don't include an id.

You might be able to just assign an id property (since most objects in the browser environment are extensible, meaning you can add properties to them), but I wouldn't recommend it. The definition of the File object changes over time, and you never know, it might get an id property that means something different from your id.

What you do instead will depend entirely on what you expect to do with the File. For instance, if this is just for client-side information, you might make your list a list of objects with id and file properties, where file is the original File object:

const fileWithId = {id: "myIdName", file: uploadedFile};
  • Related