【发布时间】:2019-02-20 09:06:34
【问题描述】:
我有一个两部分的问题。
FormData()在发送图像时未正确设置Content-Type。我该如何解决?如何将图像读取为二进制而不是
react-native中的base64
我正在尝试以 react-native 将图像上传到服务器。
使用react-native-image-picker,我可以选择图像并获取它的uri(甚至base64)。
然后我创建一个FormData() 并通过fetch 发布它(甚至尝试使用axios 和XMLHttpRequest)。但是content-type 设置为text/plain;charset=UTF-8,所以req.files 是undefined。
但是,当我手动向 send the image (shown in 'Dealing with Binary Data' section) 创建XMLHttpRequest 请求时,我可以发送图像。但是图像数据是在base64而不是binary中编码的。
XMLHttpRequest 和 FormData 的代码
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', res=>{console.log(res)} )
xhr.addEventListener('error', err=>{console.log(err)} )
xhr.open('POST', global.config.getServerAddress() + this.props.api);
xhr.setRequestHeader( 'Authorization', 'Bearer ' + global.config.token )
const formdata = new FormData();
formdata.append( this.props.label, { name: this.props.label, type: type, fileName: uri.split('/').pop() });
xhr.send(formdata);
手动XMLHttpRequest 请求的代码有效。但需要将图像数据发送为binary,而不是base64。
const boundary = "myboundary"
let data = ""
data += "--" + boundary + "\r\n"
data += 'content-disposition: form-data; '
// Define the name of the form data
+ 'name="' + this.props.label + '"; '
// Provide the real name of the file
+ 'filename="' + uri.split('/').pop() + '"\r\n'
// And the MIME type of the file
data += 'Content-Type: ' + type + '\r\n'
// There's a blank line between the metadata and the data
data += '\r\n'
// Append the binary data to our body's request
data += `data:${type};base64,` + image + '\r\n'
data += "--" + boundary + "--"
var XHR = new XMLHttpRequest()
XHR.addEventListener('load', callbackConf.callback )
XHR.addEventListener('error', callbackConf.errorCallback )
XHR.open('POST', global.config.getServerAddress() + this.props.api )
XHR.setRequestHeader( 'Authorization', 'Bearer ' + global.config.token )
XHR.setRequestHeader( 'Content-Type', 'multipart/form-data; boundary=' + boundary )
XHR.send( data )
【问题讨论】:
标签: react-native xmlhttprequest multipartform-data content-type