React Native Multipart XMLRequest - 无法识别的FormData部分

时间:2017-06-29 11:03:08

标签: javascript react-native

我正在尝试将一些文件上传到我的网站。以下代码适用于普通API请求(不包含附件)。但是当我尝试上传文件时,我会继续收到此错误回复:"Unrecognized FormData part."

export function HTTPRequest({body = {}, url = '', method = "POST", headers = {}, attachments = [], DEBUG = false}) {
    return new Promise((resolve, reject) => {
    const attachmentsCount = Object.keys(attachments).length * 1
    const ContentType = 0 < attachmentsCount ? "multipart/form-data" : "application/x-www-form-urlencoded"

    const submitXML = (xhrBody) => {
      let xhr = new XMLHttpRequest()
      xhr.open(method, url)
      headers["Content-Type"] = ContentType
      //headers["Accept"] = "application/json"
      for(var h in headers) {
        xhr.setRequestHeader(h, headers[h])
      }
      xhr.addEventListener('load', (res) => {
        switch(res.target.status) {
            case 200: return resolve(DEBUG ? res.target.response : JSON.parse(res.target.response))
            default: return reject(res)
        }
      }, false)
      xhr.onerror = e => reject(e)
      xhr.send(xhrBody)
    }

    switch(attachmentsCount) {
        case 0:
          var request = JSON.stringify(body)
          submitXML(request)
        break
      default:
        let xhrBody = new FormData()
        xhrBody.append("_photosCount", String(attachmentsCount))
        attachments.map((file, i) => {
        xhrBody.append('file', {name: file.name, src: file.src, type: file.type})
        })
        xhrBody.append('data', body)
        console.log(xhrBody);
        submitXML(xhrBody)
    }
  })
}

一旦我尝试记录它,这是FormData对象:

    0:"file"
    1: Object
    name:"FB_IMG_1498693908215.jpg"
 src:"content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F175865/ORIGINAL/NONE/1351181913"
    type:"image/jpeg"

1 个答案:

答案 0 :(得分:0)

您正在将Content-Type标头设置为multipart/form-data,而不使用描述多部分边界标记的参数。

单独保留Content-Type标头。让XMLHttpRequest从FormData对象生成它。