简体   繁体   中英

Convert base64 image to send as multipart/form-data

There is a system. The frontend is written in react and the backend in java. On the frontend part, there is an image (base64) and some fields (string) that need to be sent to the server.

'Content-Type': 'multipart/form-data'

I also know that on the backend, the image must have a MultipartFile type

I do not understand what format I need to convert the picture to. Can you please advise me?

    const formData = new FormData();
    formData.append( 'image', store.image); // store.image - base64
    formData.append( 'id-number-value', "id"); 
    formData.append( 'id-number-type', "id_card"); 

    fetch('/path', {
      method: 'POST',
      headers: { 'Content-Type': 'multipart/form-data' },
      body: formData
   } )
   .then((response) => {
      if (response.ok) {
        resolve();
      } else {
        throw new Error(response.message);
      }
   })
   .catch((error) => reject(error));

You can convert the base64 string to a blob first.

const formData = new FormData();
formData.append('id-number-value', "id");
formData.append('id-number-type', "id_card");
fetch(store.image)
    .then(res => res.blob()).then(blob => {
        formData.append('image', blob);
        fetch('/path', {
                method: 'POST',
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                body: formData
            })
            .then((response) => {
                if (response.ok) {
                    resolve();
                } else {
                    throw new Error(response.message);
                }
            })
            .catch((error) => reject(error));
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM