我想用React Native上传照片。我的Postman API尝试取得了积极的成绩。 但是React Native没做到。
反应本机功能
uploadPhoto = async response => {
const data = new FormData();
data.append("image", {
uri: response.uri,
type: response.type,
name: response.fileName,
length:response.fileSize
});
const config={
headers:{
'Content-type':'multipart/form-data'
}
}
axios
.post('https://localhost:44337/api/values',JSON.stringify(data),config)
.then(response=>{
console.log(response);
})
.catch(error=>{console.log(error);})
};
Asp.net核心方面
[HttpPost]
public IActionResult Post([FromForm]PhotoModel bookData)
{
//installation codes
return Ok();
}
型号
public class PhotoModel
{
public IFormFile image { get; set; }
}
结果:网络错误
答案 0 :(得分:1)
您可以尝试使用 React Native 代码。 希望对你有帮助。
export const uploadImages = async (formData) => {
try {
let response = await axios({
url: urlUploadImages,
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + global.TOKEN || 'Bearer ' + await AsyncStorage.getItem("@loggedInUserID:token"),
},
data: formData,
});
console.log('uploadImages API response', response)
if (response.status === 401) {
return global.UNAUTHORIZE;
} else {
// let json = await response;
if (response.status === 200) {
return response.data;
} else {
return global.FAIL;
}
}
} catch (error) {
console.log('Upload Failed', error);
}
};
答案 1 :(得分:0)
您不必从表单数据更改回JsonString。立即发送。
.post('https://localhost:44337/api/values',data,config)
答案 2 :(得分:0)
删除json.stringify并确认您设置了正确的值: const form = new FormData();
form.append('image',{ uri:“ file:/// ...”, 类型:“ image / jpg”, 名称:“ image.jpg”, });