javascript - 如何在本机中下载文件?
问题描述
我指的是这个https://github.com/joltup/rn-fetch-blob#download-to-storage-directly我已经转换了从 API 端点收到的 JSON 响应,现在我想将其转换为 CSV 文件并下载它我怎样才能做到这一点 ?当用户单击下载图标时,用户必须能够将该 JSON 响应下载为 CSV 文件。
要将 JSON 响应转换为 CSV 格式,我使用了以下代码来分隔每个字段。(另见截图)
代码:
convertToCSV = (stm_leadsitevisits, projectName) => {
// console.log("convert CSV Inside sitevisits: ",stm_leadsitevisits);
let obj = [['Sr no','Name', 'Phone', 'Email', 'Project', 'Visited at', 'Attended by', 'Source', 'Feedback']];
let data = stm_leadsitevisits;
let csvRow = [];
for(let item = 0; item<data.length; item++){
obj.push([item, data[item].name, data[item].phone, data[item].email, projectName, data[item].created_time,
data[item].user.name, data[item].source, data[item].feedback ])
}
console.log("New data: ", obj);
}
解决方案
据我了解,该库将该文件用作缓存而不是持久存储。我曾经使用两个库从磁盘读取 json 文件,我猜反过来(就像你的情况一样)也可以帮助你解决这个问题。
https://github.com/itinance/react-native-fs
https://github.com/luisfuertes/react-native-file-picker
这是我用来用 RNFS 和 RNFP 打开文件的代码,只是为了给你一个起点。
pickFile = () => {
// (1) Browse for file
DocumentPicker.show({
filetype: [DocumentPickerUtil.allFiles()],
}, (error, file) => {
// (2) Copy file to accessible path
let destPath = RNFS.DocumentDirectoryPath + '/' + file.fileName;
RNFS.copyFile(file.uri, destPath)
.then((success) => {
console.log('file copied!');
// (3) Read file content and parse to JSON
RNFS.readFile(RNFS.DocumentDirectoryPath + '/' + file.fileName, 'utf8')
.then((contents) => {
let json = JSON.parse(contents);
// (4) dispatch reducer
this.props.addJsonFile(json);
ToastAndroid.show('Imported ' + file.fileName, ToastAndroid.SHORT);
})
.catch((err) => {
console.log('Error reading file: ' + err.message);
});
})
.catch((err) => {
console.log('Error copying file: ' + err.message);
});
});
};
这是来自 RNFS github 页面的用于写入文件的代码:
var path = RNFS.DocumentDirectoryPath + '/test.txt';
// write the file
RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8')
.then((success) => {
console.log('FILE WRITTEN!');
})
.catch((err) => {
console.log(err.message);
});
刚刚在你提到的github中找到了这个部分:
let dirs = RNFetchBlob.fs.dirs
RNFetchBlob
.config({
// response data will be saved to this path if it has access right.
path : dirs.DocumentDir + '/path-to-file.anything'
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
//some headers ..
})
.then((res) => {
// the path should be dirs.DocumentDir + 'path-to-file.anything'
console.log('The file saved to ', res.path())
})
我想它不能解决您的问题,因为当承诺解决时会发生保存,并且您需要在保存之前将 JSON 转换为 CSV 。在这种情况下,我建议使用 RNFS 或向 RN-fetch-blob 添加功能请求来支持这一点。
干杯
推荐阅读
- windows - 哪种技术可以定位许多相似的基指针地址(快速)?
- ffmpeg - 使用 FFMPEG 分割视频时发出警告
- excel - 具有多个条件、多个结果和通配符的 Index/Small
- r - 涉及分类变量的 LASSO 子集选择
- c# - C# 中的字符串替换,但只有确切的字符集
- php - 从 PHP 启动并发一次性 Heroku dynos
- windows - Windows 10 上的 Julia 1.0.0 使用 PyPlot 编译器错误,因为它无法加载预期的库:.julia\\packages\\Conda\\m7vem\\deps\\usr\\python37\
- php - RegEx 仅匹配数字和最多 3 个字符
- php - 如何使用php中的标头函数从变量中读取数据
- firebase - 如何在 Flutter 应用中禁用云消息传递?