react-native - 从 React Native WebView 下载文件
问题描述
背景
我正在使用 WebView 将用户导航到下载文件的特定页面。我将 Javascript 注入 WebView 以模拟单击下载文件链接。使用 Javascript 单击链接后,该文件将在设备上打开。
我正在尝试查找将文件下载到设备的信息,而不是在 WebView 中打开它。
最初我在 IOS 中构建了这个应用程序,在那里我能够将数据作为 blob 下载,然后使用 API 将其发送到我的服务器。我想模拟相同类型的功能。
例子
// 这会在 WebView 中打开文件
const injectedJavaScript = `var confirmLink = document.querySelector("a[href='/file/download']");
if(confirmLink) { window.location.href = confirmLink.href; }
`;
this.setState({ step: "complete" });
this.webview.injectJavaScript(injectedJavaScript);
问题
如何在不在手机上打开它的情况下使用此文件?理想情况下,我希望将文件作为 blob 处理,但是我很乐意将文件下载到手机的存储中,然后可以从那里使用它。
解决方案
回答 -
从流中读取文件并将其作为 base64 使用。您可以将文件转换为 base64 并将其移动到您想要的任何位置。
例子 -
这个例子是我注入 JavaScript 来访问 Web 服务器上的文件。该文件将转换为 base64 字符串。然后我将该文件发布到我的 API 并转换回服务器上的文件。然后该文件位于我的服务器上。
const injectedJavaScript = `
fetch("https://www.example.com/somepath.do?language=en", {
method: "GET",
headers: new Headers({
Accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
Connection: "keep-alive",
Referer:
"https://www.example.com/somepath.do",
"User-Agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301",
"Content-Disposition": "attachment; filename=someFile.txt"
})
})
.then(response => {
response.body.getReader().read().then(function(result) {
return btoa(String.fromCharCode.apply(null, result.value));
}).then(function(b64) {
fetch("https://api.example.com/api/v1/endpoint", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
data: b64
})
}).then(res => {
console.log(res);
}).catch(e => {
console.log(e);
});
});
});
`;
推荐阅读
- javascript - Netsuite 脚本 2.0
- java - Java AudioInputStream如何支持负字节数的跳过
- firebase - 验证 Firestore 安全规则中的引用
- java - 如何在 jar 文件中插入和更新 sqlite 数据库
- python - 使用 Open CVadaptiveThreshold() 方法时如何知道阈值?
- java - 通过使用注释在休眠中的未知实体异常
- javascript - 元素注入后刷新DOM
- javascript - 从类中提取元素时如何使用JS更改元素的CSS属性?
- javascript - 如何使某些代码点表情符号值起作用
- meteor - Meteor/Apollo:为生产设置 Redis Pubsub?