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" class="w-full border-2 border-gray-200 rounded-3xl px-4 py-4" 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
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);