我正在尝试将文件上传到cloudinary。这是我的反应组件
的一部分...
addItem() {
...
let file = this.fileInput.value;
keywords !== "" && this.props.onAddItem(keywords, place, image);
...
}
render() {
return (
....
<Input
type="file"
innerRef={(input) => {this.fileInput = input}}
name="image"
id="image"
placeholder=""/>
)
}
这是动作文件:
export function onAddItem(keywords, place, file, id, isChangebale = false) {
return (dispatch) => {
axios.all([
axios.post('https://api.cloudinary.com/v1_1/myservername/image/upload',
{upload_preset: "mypresetname", file: file}),
axios.post('http://localhost:3001/api/items/', { keywords, place, id, isChangebale })
])
.then(axios.spread((cloudinaryRes, localRes) => {
console.log(cloudinaryRes, localRes);
}))
我收到错误xhr.js:178 POST https://api.cloudinary.com/v1_1/testovich/image/upload 400 (Bad Request)
和响应标头"X-Cld-Error: Unsupported source URL: C:\fakepath\2017-12-07_19-06-445.png"
当我使用postman测试时,我的回答是正确的。
所以当将文件从rect组件传递到动作文件时,我似乎做错了。如何将正确的路径/文件传递给cloudinary?
答案 0 :(得分:1)
有两个错误: 1.在react组件中应该
let file = this.fileInput.files[0];//I upload only one file
代替
let file = this.fileInput.value;
实际文件
导出功能onAddItem(关键字,位置,图像,ID,isChangebale = false){ const formData = new FormData(); formData.append(“ file”,image); formData.append(“ upload_preset”,“ mypresetname”);
返回(发送)=> { axios.all([ //使用Axios的AJAX上传请求) axios.post('https://api.cloudinary.com/v1_1/myservername/image/upload', formData,
代替:
export function onAddItem(keywords, place, file, id, isChangebale = false) {
return (dispatch) => {
axios.all([
axios.post('https://api.cloudinary.com/v1_1/myservername/image/upload',
{upload_preset: "mypresetname", file: file}),
答案 1 :(得分:0)
将图像转换为类似const base64Img = data:image/jpg;base64,${file.data};
的base64
file.data
代表来自图像选择器响应的数据属性。
然后我将base64Img传递给像
return RNFetchBlob.fetch('POST', apiUrl, headerProps, [ { name: 'file', fileName: file.fileName, type: file.type, data: base64Img } ]);
希望对您有所帮助。