Home > OS >  Convert an image from file upload to blob to post to database VueJS
Convert an image from file upload to blob to post to database VueJS

Time:06-14

I have a form with multiple inputs, one being of type="file". Where I want to be able to upload an image and then post the form to the api so it's stored on the database.

<input name="image"  type="file" placeholder="Event Image" />

However when I enter all the form values (including file uploading and image) I get this error:

"error TypeError: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'."

I'm pushing the values into formdata which is then posted to the API

...
 methods: {
      async onSubmit(values) {
         console.log("button submitted")
                  try {
                     var formdata = new FormData();
                     formdata.append("name", values.eventname);
                     formdata.append("description", values.eventdescription);
                     formdata.append("image", values.image, "Image");
...

How can I convert the file type to blob so it can be uploaded? Thank you

CodePudding user response:

You need to take the values.image, console.log the response from it so see how the data is structured. There should be a string value in there that you may need to split at . so that you can take the MIME type of the file that you have uploaded as you need this to create the blob.

The structure of a Blob is like so.

new Blob(blobParts, options);

/**
 * blobParts is an array of Blob/BufferSource/String values.
 * options: option object:
 *    type - Blob type, usually MIME-type e.g image/png
 *    endings - whether to transform end-of-line to make the Blob corrospond to current OS newlines.
 */

You should also be able to turn this into a Blob by calling the .blob() function on the file that has been uploaded.

A dummy is as so:

// your file name in the second param should be constructed of the string that you have logged and split earlier.
var fileToUpload = new File([Blob], 'some_file_name.jpg', {
  type: "image/jpg", // this should be from your string split of the filename to check the file upload type.
  lastModified: new Date(),
});

form.append("image", fileToUpload);

CodePudding user response:

For the experience that I have gained on the subject, I can tell you that in order to create a FormData, the second parameter must necessarily be converted into a Blob file. Your code is not very clear to me to be honest, but if you want to learn more about the subject, I will give you the section on FormData of the official Javascript guide:

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

  • Related