所以我想上传 对象作为数据 并归档为注释 使用 axios 到 api
uploadToServer= () => {
const file =this.state.photo
let data2 ={sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
let data = new FormData()
data.append('data[sale_id]', '1')
data.append('data[note_type_id]', '4')
data.append('data[description]', "test")
data.append('data[note_content_item]', "test")
console.log(data)
axios({
url: api',
method: 'POST',
data: data,
headers: {
'Content-Type' : 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(resp => console.log(resp.data.response))
.catch(error => console.error(error));
}
首先我尝试使用没有注释的数据,我可以在邮递员中完成
但是我的代码出现错误
消息:“无法保存文件” 响应代码:10
当您使用react-native时,您不需要“form-data”包。因为 React Native Polyfills 标准 FormData api 并将其导出为全局。
第二个问题是axios自动将表单数据转换为字符串,因此您需要根据请求使用transformRequest配置来覆盖它。
import { AxiosRequestConfig } from "axios";
const FormData = global.FormData;
const axiosInstance = axios.create({
baseURL: 'example.com', // use with scheme
timeout: 30000,
headers: {
"X-Platform": 'iOS',
"X-App-Build-Number": '1.0.0',
},
});
const formData = new FormData();
formData.append("userId", "123456");
formData.append("file", {
uri: "/dev/sda/abc.png",
type: "image/png",
name: "abc.png",
});
const config: AxiosRequestConfig = {
method: "post",
url: "/process/start",
responseType: "json",
headers: {
'Content-Type': 'multipart/form-data',
// if backend supports u can use gzip request encoding
// "Content-Encoding": "gzip",
},
transformRequest: (data, headers) => {
// !!! override data to return formData
// since axios converts that to string
return formData;
},
onUploadProgress: (progressEvent) => {
// use upload data, since it's an upload progress
// iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902}
},
data: formData,
};
// send post request and get response
const response = await axiosInstance.request(config);
您没有正确构建
FormData
,试试这个:
let data = {sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
const formData = new FormData();
formData.append('data', JSON.stringify(data));
formData.append('Note', {
uri: "file://" //Your Image File Path
type: 'image/jpeg',
name: "imagename.jpg",
});
axios({
url : api,
method : 'POST',
data : formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(function (response) {
console.log("response :", response);
})
.catch(function (error) {
console.log("error from image :");
})
formData.append("文件", { uri: //文件.uri, type:"multipart/form-data", // 类型必须是 multipart/form-data 名称:文件名, });
当我们在 React Native Web 上上传图像时,它返回以下错误 错误:多部分:表单意外结束,状态:400
解决方案
我已经修复了这个问题,请参阅下面随附的代码以获取解决方案
const uploadOnWeb = async (uri: string) => {
const filename = ${Date.now()}.png;
const formData = new FormData();
const base64Image = uri.replace(/^data:image/\w+;base64,/, '');
const binary = atob(base64Image);
const array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
const file = new Blob([new Uint8Array(array)], { type: 'image/png' });
formData.append('file', file, filename);
try {
const token = await Storage.getItem('authToken');
const response = await fetch(${REACT_APP_API_URL}/upload/${filename}, {
method: 'POST',
headers: {
Authorization: Bearer ${token},
},
body: formData,
});
if (response.status === 201) {
alert('Image uploaded successfully');
} else {
alert('There is some error uploading image');
}
} catch (error) {
alert('There is some error uploading image');
}
};
这可能对你有帮助:
import {Platform} from 'react-native';
import axios from 'axios';
const upload = async readPath => {
console.log('path', readPath);
const URL = 'your-url';
const headers = {
headers: {
'Content-Type': 'multipart/form-data',
Accept: 'application/json',
Authorization: `Bearer ${projectSecret}`,
},
};
const formData = new FormData();
const file = {
uri:
Platform.OS === 'android' ? `file:///${readPath}` : readPath,
type: 'text/plain',
name: name,
};
formData.append('file', file);
await axios
.post(URL, formData, headers, {
timeout: 3000,
})
.then(async response => {
console.log(response.data);
})
.catch(error => {
console.log('error : ', error);
});
};