【发布时间】:2019-11-27 20:21:30
【问题描述】:
React Native 的新手。我正在尝试使用 FormData 使用来自Spencer Carli 的以下示例使用 fetch API 上传图像和数据。我的后端工作正常,当我使用邮递员时,图像上传到数据库存储没有任何问题。但是当我尝试通过移动设备上传图片时,我得到了
upload error [SyntaxError: JSON Parse error: Unexpected identifier "Tunnel"]
下面是我的代码
const createFormData = (photo, body) => {
const data = new FormData();
data.append('file', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', ''),
});
Object.keys(body).forEach(key => {
data.append(key, body[key]);
});
return data;
};
const uploadPhotoHandler = async (photo) => {
const token = await AsyncStorage.getItem('token');
fetch('http://ba9737b7.ngrok.io/post', {
headers: {'Authorization': 'Bearer ' + token},
method: 'POST',
body: createFormData(photo, {
title: 'Golden twisted knots',
postType: 'hair',
duration: 45}),
})
.then(response => response.json())
.then(response => {
console.log('upload succes', response);
alert('Upload success!');
})
.catch(error => {
console.log('upload error', error);
alert('Upload failed!');
});
};
我认为问题出在这一行
.then(response => response.json())
但我不知道为什么。
【问题讨论】:
-
您在回复中得到了什么? `Object.keys(body).forEach(key => { data.append(key, body[key]); });` 的目的是什么,你只需要发送文件对象
标签: react-native upload fetch multipartform-data form-data