2017-06-29 71 views
0

我想上傳一些文件到我的網站。以下代碼適用於正常的API請求(不包括附件)。但是當我嘗試上傳文件時,我一直在收到此錯誤響應:"Unrecognized FormData part."反應本機多部分XMLRequest - 無法識別的FormData部分

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" 

回答

0

你設置Content-Type頭,以multipart/form-data沒有描述多界碑參數。

單獨留下Content-Type標題。讓XMLHttpRequest從FormData對象生成它。

+0

它的工作表示感謝。但是當我追加文件數據時,我不添加描述多部分邊界標記的參數嗎? – Raymond

+0

@Raymond - 不包含你明確指定的內容類型的HTTP頭,但不包含邊界參數。數據本身有邊界,但解析器不知道它們是什麼。 – Quentin