簡體   English   中英

轉換 base64 圖像以作為 multipart/form-data 發送

[英]Convert base64 image to send as multipart/form-data

有一個系統。 前端是用 react 編寫的,后端是用 java 編寫的。 在前端部分,有一個圖像(base64)和一些需要發送到服務器的字段(字符串)。

“內容類型”:“多部分/表單數據”

我也知道在后端,圖像必須具有MultipartFile類型

我不明白我需要將圖片轉換為什么格式。 你能告訴我嗎?

    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));

您可以先將 base64 字符串轉換為 blob。

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));
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM