File object with custom properties

I want to store files on server with custom File properties. On client side im adding properties:

let file = new File([blob], 'flower.jpg')
file.custom = "another properties"

this gives me

custom:"another properties"
lastModified:1524742832101
lastModifiedDate:Thu Apr 26 2018 13:40:32 GMT+0200 (W. Europe Daylight Time {}
name:"flower.jpg"
size:845941
type:"image/jpeg"
webkitRelativePath:""

When i send this file to my node server the custom property is deleted. Im using formData and multer for file upload.

fieldname: 'images',
originalname: 'flower.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
size: 845941

Is there a way to store the file including custom properties?

Upvotes: 13

Views: 9421

Answers (3)

Dev
Dev

Reputation: 441

In my own case, I just sent the FormData with the additional property as array key-value pairs to the backend, for example:.

let file = new File([blob], 'flower.jpg');
let formData = new FormData();
formData.append("file[property]", file);

Upvotes: 0

Oseme Abulu
Oseme Abulu

Reputation: 27

Use Object.defineProperty() like this

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

object1.property1 = 77;
// throws an error in strict mode

console.log(object1.property1);
// expected output: 42

More details here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Upvotes: 1

John Hampton
John Hampton

Reputation: 31

I ran into a similar scenario with multer / express and ended up appending an additional property for each file being uploaded. Then pulled the additional property, matched on file name, from the req.body on the server. Our UI prevents duplicate file names, so this worked well for us.

const data = new FormData();

files.forEach((file) => {
  data.append('form-key', file);
  data.append(file.name, file.identifier);
});

Upvotes: 3

Related Questions