如何通过HTTP请求从图像Uri发送图像? (React Native和Django后端) [英] How to send image from image Uri through HTTP request? (React Native and Django Backend)

查看:240
本文介绍了如何通过HTTP请求从图像Uri发送图像? (React Native和Django后端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I’m using Expo’s image picker and I’m getting this output:

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,
}

我可以渲染我的图片,但我刚刚意识到该网址是手机的本地URI

I could render my image, but I just realized that the URL is the phone’s local URI.

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

I’m using Redux-Thunk and Axios to send HTTP POST request:

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});

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

!! sorry for the complication but image variable name; image is uri for the image. I didn't want to change the name of original variable name

并且在服务器上,它正在打印

and on server, it's printing

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

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

I found that gzip compression is a way to send image data. Does it help?

推荐答案

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

Another option is to convert your image to base64 and send the string. Downsize is that usually the base64 strings has a bigger size than the image itself.

这样的事情:

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(); 
}

这篇关于如何通过HTTP请求从图像Uri发送图像? (React Native和Django后端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆