我正在设置标题和正文,使用fetch with Post将图像上传到服务器上。我收到响应代码200,但它没有上传图像,但其余的数据正在上传。
以下是正文代码:
export default function setRequestBody(imagePath){
let boundry = "----WebKitFormBoundaryIOASRrUAgzuadr8l";
let body = new FormData();
body.append("--"+boundry+"\r\n");
body.append("Content-Disposition: form-data; name=imageCaption\r\n\r\n");
body.append("Caption"+"\r\n");
body.append("--"+boundry+"\r\n");
body.append("Content-Disposition: form-data; name=imageFormKey; filename =iimageName.pngg \r\n");
body.append("Content-Type: image/png \r\n\r\n");
body.append({uri : imagePath});
// appened image Data Here
body.append("\r\n");
body.append("--"+boundry+"--\r\n");
return body
}
请帮忙。我犯的是什么错误。 :(
答案 0 :(得分:6)
我找到了解决方案:
let body = new FormData();
body.append('photo', {uri: imagePath,name: 'photo.png',filename :'imageName.png',type: 'image/png'});
body.append('Content-Type', 'image/png');
fetch(Url,{ method: 'POST',headers:{
"Content-Type": "multipart/form-data",
"otherHeader": "foo",
} , body :body} )
.then((res) => checkStatus(res))
.then((res) => res.json())
.then((res) => { console.log("response" +JSON.stringify(res)); })
.catch((e) => console.log(e))
.done()
** filename是可选的......
答案 1 :(得分:4)
问题是body.append({uri : imagePath});
因为本机JSC不支持File和Blob,所以你必须使用库。
react-native-fetch-blob对此有非常好的支持,例如README.md
RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
// element with property `filename` will be transformed into `file` in form data
{ name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
// custom content type
{ name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
// part file from storage
{ name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
// elements without property `filename` will be sent as plain text
{ name : 'name', data : 'user'},
{ name : 'info', data : JSON.stringify({
mail : 'example@example.com',
tel : '12345678'
})},
]).then((resp) => {
// ...
}).catch((err) => {
// ...
})