我是第一次接触react-native。我想使用rn-fetch-blob上传一个带有另一个参数'comment‘的文件。我能够选择一个文件,并使用react-native-document-picker包获得文件的路径、名称、类型和大小。文件的详细信息日志为:
console.log(res.uri, res.type, res.name, res.size);
Output:
'content://com.android.providers.downloads.documents/document/1445', 'text/html', 'hello.webp', 21476
我只是简单地使用了fetch函数和方法'POST‘,这一点我不确定。
var file = {
name: this.type,
filename : this.name,
data: RNFetchBlob.wrap(this.uri)
};
var文件的日志:
{ name: 'text/html',
│ filename: 'hello.webp',
└ data: 'RNFetchBlob-content://content://com.android.providers.downloads.documents/document/1445' }
方法:
fetch('https://beta.hellonepal.io/api/v1/comments',
{
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type' : 'multipart/form-data',
'Authorization': 'Bearer '+ global.apiToken,
},
body: JSON.stringify(
{
comment: this.state.newComment,
comment_file : file
})
})
.then(response => {
return response.json()
})
.then(RetrivedData => {
console.log(RetrivedData);
})
.catch(err => {
// Do something for an error here
console.log('Error in adding a comment');
});
});
我尝试使用RNFetchBlob方法,但不知道如何传递其他参数:
const url = "https://beta.hellonepal.io/api/v1/comments";
RNFetchBlob
.config({
trusty : true
})
.fetch(
'POST',
url, {
'Content-Type' : 'multipart/form-data',
}, file)
.then((res) => {
console.log(res);
callback(res);
})
.catch((errorMessage, statusCode) => {
console.log("Error: "+ errorMessage + " - " + statusCode);
})
发布于 2019-07-25 14:47:40
您可以更改上传,如下所示:
Content-Type
应为json,因为您的body
类型为json
let formdata = new FormData();
formdata.append("comment", this.state.newComment);
formdata.append("comment_file", file);
RNFetchBlob.fetch('POST', 'https://beta.hellonepal.io/api/v1/comments', {
Authorization : 'Bearer '+ global.apiToken,
body: formdata,
'Content-Type' : "multipart/form-data",
})
.then((response) => response.json())
.then((RetrivedData) => {
console.log(RetrivedData);
})
.catch((err) => {
console.log('Error in adding a comment');
})
https://stackoverflow.com/questions/57195260
复制相似问题