react-native - 如何在 Zendesk API 上上传图像?
问题描述
我正在使用下面的功能在 zendesk 上上传图像。Zendesk 要求上传二进制图像,并且当我在 Firebase 上上传时,获取 blob 图像方法有效。这些函数得到响应 201 但当您检查图像时,它只是一个白色方块。我认为图像在上传过程中损坏了。
imageUri 从 expo-image-picker 返回,如下所示:
文件:/data/user/0/host.exp.exponent/cache/ExperienceData/.../ImagePicker/8543faa5-b996-46cd-9554-ce9afb61385b.jpg
const uploadImages = async (imageUri) => {
try {
const filename = getFilenameFromImagePicker(imageUri);
const resImg = await fetch(imageUri);
const blobImg = await resImg.blob();
const response = await axios.post(`uploads?filename=${filename}`, {
blobImg
}, {
auth: {
username: membersEmail + '/token',
password: ZENDESK_API_KEY
},
headers: {
'Content-Type': 'application/binary',
}
})
return response.data;
}
catch (error) {
captureException(error);
return null;
}
}
将图像更改为二进制以便可以将其上传到 zendesk 的最佳方法是什么?
以下是 Zendesk 用于上传图像的文档中的 curl 语句
curl "https://{subdomain}.zendesk.com/api/v2/uploads?filename=myfile.dat&token={optional_token}" \
-data-binary @file.dat \
-v -u {email_address}:{password} \
-H "Content-Type: application/binary" \
-X POST
解决方案
经过大量测试,我能够使其工作。在这里发布我想出的答案,以防其他人有同样的问题。
async function uploadToServer(sourceUrl) {
// first get our hands on the local file
const localFile = await fetch(sourceUrl);
// then create a blob out of it (only works with RN 0.54 and above)
const fileBlob = await localFile.blob();
// then send this blob to filestack
const serverRes = await fetch('https://www.yourAwesomeServer.com/api/send/file', { // Your POST endpoint
method: 'POST',
headers: {
'Content-Type': application/binary,
},
body: fileBlob, // This is your file object
});
const serverJsonResponse = await serverRes.json();
return serverJsonResponse;
}
推荐阅读
- angular5 - 绑定 html 从 Angular 5 下拉
- python - 使用 BeautifulSoup 和 Requests 从 xml 文件打印数据
- arduino - 在 Arduino Uno 上的 2 个引脚之间传递信息
- php - 通过 HTTP 向 php 文件发送/接收数据(作为服务器)
- python-2.7 - 将带有时区的日期时间对象转换为分钟
- pandas - 为什么使用 pandas 时 cmd 出现语法错误?这段代码有什么问题-
- java - 将两个类相互连接
- javascript - 保存上下文
- javascript - React-dates 如何识别用户选择数据的方式
- javascript - css关键帧动画反转