【问题标题】:convert react-native-signaturepad output to formData?将 react-native-signaturepad 输出转换为 formData?
【发布时间】:2018-09-28 09:19:59
【问题描述】:

我需要将我的 react-native-signaturepad 输出作为图像上传到服务器。我已经尝试过以下代码

//this.state.base64 is signaturepad output
let  blob = new Blob([this.state.base64], {type: 'image/png'});
    alert(blob.size);
      var fd = new FormData()
      fd.append('file',blob,"Sign.png")
         let url="http://xxxxxx/xxxx/xxx/";
        fetch(url, {
          method: 'POST',
          headers: {        
            'Content-Type': 'multipart/form-data'
          },
          body: fd
        }).then(function (response) {
               alert("dfdfdfdfd")
        });

使用上面的代码我得到了

"多部分正文必须至少有一个部分"

错误请任何人帮我解决这个问题

谢谢

【问题讨论】:

  • 您确定this.state.base64 是在您调用new Blob 时设置的吗?该错误使我相信 formData 主体为空,这表明您的 blob 可能未正确创建。我的另一个建议是尝试将 axios 用于您的发布请求,看看是否有任何不同。您还可以尝试使用 npmjs.com/package/b64-to-blob 之类的库来创建您的 blob,看看是否存在问题。
  • 我正在获取 blob 大小值
  • 我试过这个包 npmjs.com/package/b64-to-blob 这个抛出错误 "cannot fint variable atob"
  • 您可以在此处查看解决方案以定义 atob:stackoverflow.com/questions/23097928/… 我知道这似乎需要付出很多努力,但调试过程更需要尝试找出问题所在。然后您可以稍后重构。

标签: javascript reactjs react-native fetch multipartform-data


【解决方案1】:

我认为由于Blob(blobParts\[, options\]) 支持的blobParts 类型是

Array 中的 ArrayBufferArrayBufferViewBlobDOMString 对象或任何此类对象的混合,它们将被放入 Blob。 DOMStrings 被编码为UTF-8

因此,将base64 转换为 blob 的简单方法是使用 fetch api

let base64Url = // Your Base 64 URL

fetch(base64Url)
.then(res => res.blob())
.then(blob => //Use the blob here)

然后您可以根据需要执行其余操作。

【讨论】:

    猜你喜欢
    • 2020-05-25
    • 2020-04-17
    • 2019-03-15
    • 1970-01-01
    • 2021-06-18
    • 2017-07-22
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多