繁体   English   中英

如何通过HTTP请求从图像Uri发送图像? (React Native和Django后端)

[英]How to send image from image Uri through HTTP request? (React Native and Django Backend)

我正在使用Expo的图像选择器,我得到了这个输出:

Object {
  "cancelled": false,
  "height": 468,
  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540jbaek7023%252Fstylee/ImagePicker/9a12f0a3-9260-416c-98a6-51911c91ddf4.jpg",
  "width": 468,
}

我可以渲染我的图像,但我才意识到URL是手机的本地URI

我正在使用Redux-Thunk和Axios发送HTTP POST请求

export const sendPost = ( imageUri, title, content ) => async dispatch => {
  let response = await axios.post(`${ROOT_URL}/rest-auth/registration/`, {
    image, <<<<- I can't put image uri here :( it's LOCAL path
    title,
    content
  })

  if(response.data) {
    dispatch({ type: POST_CREATE_SUCCESS, payload: response.data.token })
  } else {
    dispatch({ type: POST_CREATE_FAIL })
  }
}

更新我更改了请求调用

let headers = { 'Authorization': `JWT ${token}`};
  if(hType==1) {
    headers = { 'Authorization': `JWT ${token}`};
  } else if (hType==2) {
    headers = { 'Authorization': `Bearer ${token}`};
  }

let imageData = new FormData();
imageData.append('file', { uri: image });
let response = await axios.post(`${ROOT_URL}/clothes/create/`, {
    image: imageData,
    text, bigType, onlyMe ...
  }, {headers});

抱歉复杂但图像变量名称; imageimageuri 我不想更改原始变量名的名称

在服务器上,它正在打印

'image': {'_parts': [['file', {'uri': 'file:///data/user/0/host.exp.exponent
    /cache/ExperienceData/%2540jbaek7023%252Fstylee/
    ImagePicker/78f7526a-1dfa-4fc9-b4d7-2362964ab10d.jpg'}]]}

我发现gzip压缩是一种发送图像数据的方法。 有帮助吗?

另一种选择是将图像转换为base64并发送字符串。 缩小通常是base64字符串的大小通常比图像本身大。

像这样的东西:

function readImage(url, callback) {   
    var request = new XMLHttpRequest();
    request.onload = function() {
       var file = new FileReader();
       file.onloadend = function() {
          callback(file.result);
       }
       file.readAsDataURL(request.response);
    };   
    request.open('GET', url);   
    request.responseType = 'blob';              
    request.send(); 
}

它必须是一个本地URI,没有问题,你还有什么指向图像。

现在要上传图像,首先应将其包装在FormData中:

// add this just above the axios request
let img = new FormData();
img.append('file', { uri: imageUri });

然后在你的axios请求体内添加:

image: img,

编辑 :这个问题的当前形式是无法回答的。

我在我的一个项目中使用与React-native相同的Expo的图像选择器作为OP,一切正常,FormData没有问题。

几天前在一次stackoverflow聊天中与OP交谈,并将请求剥离到一个图像后,服务器开始抛出编码错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 168: invalid start byte

所以问题是OP的Django后端在解析图像时没有正确设置,而不是图像本身的发送 - 这使得问题无法回答。

你不能使用react-native-fetch-blob .....

 import RNFetchBlob from " react-native-fetch-blob" PostRequest(PATH){ RNFetchBlob.fetch('POST', "[URL]", { "x-session-id": "SESSION_ID", //or Custom headers 'Content-Type': 'multipart/form-data', }, [ { name: 'image', filename: 'vid.jpeg', data: RNFetchBlob.wrap(PATH) }, // custom content type ]).then((res) => { console.log(res) }) .catch((err) => { console.log(err) // error handling .. }) } } 

用于参考react-native-fetch-blob

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM