hel*_*eer 6 javascript image http reactjs 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,
}
Run Code Online (Sandbox Code Playgroud)
我可以渲染我的图像,但我才意识到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 })
}
}
Run Code Online (Sandbox Code Playgroud)
更新我更改了请求调用
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});
Run Code Online (Sandbox Code Playgroud)
!抱歉复杂但图像变量名称; image是uri为了形象.我不想更改原始变量名的名称
在服务器上,它正在打印
'image': {'_parts': [['file', {'uri': 'file:///data/user/0/host.exp.exponent
/cache/ExperienceData/%2540jbaek7023%252Fstylee/
ImagePicker/78f7526a-1dfa-4fc9-b4d7-2362964ab10d.jpg'}]]}
Run Code Online (Sandbox Code Playgroud)
我发现gzip压缩是一种发送图像数据的方法.有帮助吗?
它必须是本地 URI,这没有问题,否则您将如何指向图像。
\n\n现在要上传图像,您应该首先将其包装在 FormData 中:
\n\n// add this just above the axios request\nlet img = new FormData();\nimg.append('file', { uri: imageUri });\nRun Code Online (Sandbox Code Playgroud)\n\n然后在 axios 请求正文中添加:
\n\nimage: img,\nRun Code Online (Sandbox Code Playgroud)\n\n编辑:这个问题目前的形式是无法回答的。
\n\n我在我的一个项目中使用与 React-native 相同的 Expo\xe2\x80\x99s 图像选择器作为 OP,一切正常,FormData 没有问题。
\n\n几天前,在 stackoverflow 聊天中与 OP 交谈并将请求简化为图像后,服务器开始抛出编码错误:
\n\nUnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 168: invalid start byte\nRun Code Online (Sandbox Code Playgroud)\n\n所以问题在于 OP 的 Django 后端在解析图像时没有正确设置,而不是图像本身的发送 - 这使得问题无法回答。
\n另一种选择是将图像转换为 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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3011 次 |
| 最近记录: |