0
votes

A form I use to upload a book cover to Cloudinary has an input type='file' on it. However I'd like to allow no image upload too that is when the form submits there is no file provided to input type='file'. Cloudinary responds with Request failed with status code 400.

This is how I try to mock a file to upload it to Cloudinary inside an action.

export const addBook = (bookData, history) => (dispatch) => {
    const cloudinaryUrl = 'https://api.cloudinary.com/v1_1/*****/upload';
    const cloudinaryUploadPreset = '*****';

    const formData = new FormData();

    bookData.cover[0] && formData.append('file', bookData.cover[0]);

    if (!bookData.cover[0]) {
        const blob = new Blob([''], { type: 'image/png' });
        blob['lastModifiedDate'] = '';
        blob['name'] = 'mockImageFile';
        blob['webkitRelativePath'] = '';
        blob['size'] = 7654;

        formData.append('file', blob);

        /* const f = new File([''], 'filename', { type: 'image/jpeg' });
        formData.append('file', f); */
    }

    formData.append('upload_preset', cloudinaryUploadPreset);

    axios({
        url: cloudinaryUrl,
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: formData
    })
... ...

Still Cloudinary responds with Request failed with status code 400. How do I convince it to take a programmatically created 'file'?

The goal is to handle an upload with no file.

2

2 Answers

1
votes

You need to convert blob data to a data URI which will be accepted by the file parameter to Cloudinary's upload method.

Please try below codebase to convert blob data to data URI. which you can append it to formdata.

const blob = new Blob([""],{ type: "image/png" }); blob["lastModifiedDate"] = ""; blob["name"] = "mockImageFile"; blob["webkitRelativePath"] = "";

blob["size"]=7654;

var reader = new FileReader();

var blob_base64data; reader.readAsDataURL(blob); reader.onloadend = function() { blob_base64data = reader.result; }; formData.append("file", blob_base64data);

1
votes

You can either perform a check for an empty file before uploading to Cloudinary and not upload to Cloudinary if there is no file or you can use a default image everytime there is no file uploaded instead of creating a blob.