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

标签 javascript image reactjs http react-native

我正在使用 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 })
  }
}

UPDATE 我更改了请求调用

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

!!对不起,复杂但图像变量名称; image 是图像的 uri。我不想更改原始变量名的名称

在服务器上,它正在打印

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

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

最佳答案

另一种选择是将图像转换为 base64 并发送字符串。 Downsize 通常是 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(); 
}

关于javascript - 如何通过 HTTP 请求从图像 Uri 发送图像? (React Native 和 Django 后端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951617/

相关文章:

javascript - EmberJS : Render default template

html - 在移动设备上获取损坏的图像

javascript - 使用 MediaQuery 时 Radium-React 报告 "please wrap your application in the StyleRoot component"

reactjs - react 语法错误: Expected corresponding JSX closing tag for <img>

javascript - 如何删除作为 jQuery 中对象的属性传递的事件处理程序?

javascript - 如果我将 null 除以 javascript/Angular 中的数字,如何得到 null?

javascript - 如果eval()无法评估给定的字符串,则显示 “Syntax Error”

python - 如何使用 Python 解码内存中的 JPEG XR 文件

jquery - 单击文本 li 时用图像填充 div

json - 什么是 axios.defaults.headers.post 'content-type' = 'application/json'