gpt4 book ai didi

javascript - 如何在React Native中下载文件?

转载 作者:行者123 更新时间:2023-12-03 00:18:31 25 4
gpt4 key购买 nike

我指的是这个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())
})

我想这并不能解决您的问题,因为保存是在 promise 解决时发生的,并且您需要在保存之前将 JSON 转换为 CSV。在这种情况下,我建议使用 RNFS 或向 RN-fetch-blob 添加功能请求来支持这一点。

干杯

关于javascript - 如何在React Native中下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54436254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com