beldier
beldier

Reputation: 13

Convert buffer to file [FileCollection:meteor/ostrio:files]

when i get the image from the input i have to convert it to a buffer to make some operations with the image, so as a result a i have a buffer instead of file. im using FileCollection in meteor to store the image in mongo collection

uploadIt(e) {
  e.preventDefault();
  var reader = new FileReader();
  var buffer;
  var file = e.currentTarget.files[0];
  if (e.currentTarget.files && e.currentTarget.files[0]) {
    reader.onload = function(e){
      buffer = new Uint8Array(reader.result);
      // some operations over the buffer
  };
  reader.readAsArrayBuffer(file);
  if (file) {
    let uploadInstance = CourseFilesCollection.insert({
      file: buffer,
      ..
      ..
    })
  }
}

but when i insert it got this error

message: "[FilesCollection] [insert] Have you forget to pass a File itself?

the code originally was

 if (file) {
    let uploadInstance = CourseFilesCollection.insert({
      file: file,
      ..
      ..
    })
  }

but since i had to perfom operations over the the image i need to someway conver the buffer to file any ideas how to solve this ?

Upvotes: 1

Views: 957

Answers (1)

Endless
Endless

Reputation: 37786

Short answer

use the file constructor to turn bits back to a file container:

file: new File([buffer], file.name, file)

you could try using blob also with wider browser support... but if you want to use the latest tech, then:

async uploadIt (evt) {
    evt.preventDefault()
    const file = evt.currentTarget.files[0]
    if (!file) return
    const buffer = new Uint8Array(await file.arrayBuffer())
    // some operations over the buffer

    const uploadInstance = CourseFilesCollection.insert({
        file: new File([buffer], file.name, file)
    })
}

Upvotes: 1

Related Questions