13

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?

2
  • Store your custom properties in an other object and send it with your file object to your API. Commented Apr 26, 2018 at 11:47
  • thx. Yes this is my next move if custom properties cant be added. But it would be nice to embed custom information within the File object itself. Commented Apr 26, 2018 at 11:52

3 Answers 3

3

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);
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Not working at all
This solution didn't work for me.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.