Hello This is my first time trying to build an API. What I am trying to do is send an image saved on my phone through react-native to a loopback container that would save the image on my computer. I'm having trouble formatting the form data correctly so the image will be accepted by loopback. I've been trying:
您好这是我第一次尝试构建API。我要做的是将保存在手机上的图像通过本地反应发送到环回容器,以便将图像保存在我的计算机上。我无法正确格式化表单数据,因此环回将接受图像。我一直在努力:
let photo = {names: 'file', uri:'file:///storage/emulated/0/Pictures/IMG_20161028_094032.jpg'}
let formdata = new FormData();
formdata.append(photo.names, photo.uri)
fetch('http://192.168.0.15:3000/api/containers/container2/upload',{
method: 'POST',
body: formdata
}).then(response => {
}).catch(err => {
})
The response I get back is:
我得到的回应是:
_bodyText: '{"result":{"files":{},"fields":{"file":["file:///storage/emulated/0/Pictures/IMG_20161028_094032.jpg"]}}}' }
Which is incorrect because the file should be in "files" and not "fields"
这是不正确的,因为该文件应该在“文件”而不是“字段”
1 个解决方案
#1
1
Try using xhr
instead of fetch
. This is the example provided by Facebook for this scenario...
尝试使用xhr而不是fetch。这是Facebook为此场景提供的示例...
// Polyfill for XMLHttpRequest2 FormData API, allowing multipart POST requests with
// mixed data (string, native files) to be submitted via XMLHttpRequest.
var photo = {
uri: uriFromCameraRoll,
type: 'image/jpeg',
name: 'photo.jpg',
};
var body = new FormData();
body.append('authToken', 'secret');
body.append('photo', photo);
body.append('title', 'A beautiful photo!');
xhr.open('POST', serverURL);
xhr.send(body);
#1
1
Try using xhr
instead of fetch
. This is the example provided by Facebook for this scenario...
尝试使用xhr而不是fetch。这是Facebook为此场景提供的示例...
// Polyfill for XMLHttpRequest2 FormData API, allowing multipart POST requests with
// mixed data (string, native files) to be submitted via XMLHttpRequest.
var photo = {
uri: uriFromCameraRoll,
type: 'image/jpeg',
name: 'photo.jpg',
};
var body = new FormData();
body.append('authToken', 'secret');
body.append('photo', photo);
body.append('title', 'A beautiful photo!');
xhr.open('POST', serverURL);
xhr.send(body);