Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 306
Bernt Christian Egeland Avatar asked Apr 26 '18 11:04

Bernt Christian Egeland


2 Answers

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

like image 59
Oseme Abulu Avatar answered Sep 21 '22 16:09

Oseme Abulu


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);
});
like image 38
John Hampton Avatar answered Sep 21 '22 16:09

John Hampton