React native 如何使用rn fetch blob在react native中上载文件?
我是个新来的本地人。我想用rn fetch blob上传一个带有另一个参数“comment”的文件。我能够使用react native document picker软件包选择一个文件并获得文件的路径、名称、类型和大小。文件详细信息的日志为:React native 如何使用rn fetch blob在react native中上载文件?,react-native,file-upload,fetch,React Native,File Upload,Fetch,我是个新来的本地人。我想用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',
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);
})
您可以按如下方式更改上载:
内容类型
应该是json,因为您的正文
类型是json
let formdata=new formdata();
formdata.append(“comment”,this.state.newComment);
追加(“注释文件”,文件);
RNFetchBlob.fetch('POST','https://beta.hellonepal.io/api/v1/comments', {
授权:'持有人'+global.apiToken,
正文:formdata,
“内容类型”:“多部分/表单数据”,
})
.then((response)=>response.json())
.然后((检索数据)=>{
console.log(检索数据);
})
.catch((错误)=>{
log(“添加注释时出错”);
})
将其作为数组传递:@Horst我尝试使用数组,只发布注释而不发布文件。如何上传文件?帮我做这个。谢谢。我试过了,但无法上传文件。评论和文件都是空的,没有发现任何错误。哦,对不起,我错了,内容类型应该是json,因为你的主体类型是json。我修改了我的答案。我将“内容类型”更改为json,但没有任何进展。注释和文件都为空。只有一个文件Uri就足以上传吗?如何将“var文件”视为实际文件?帮我做这个。谢谢。以表单数据形式发送正文可能会有所帮助。更新了我的答案