[英]How to download file in react native?
我指的是這個https://github.com/joltup/rn-fetch-blob#download-to-storage-direct我已經轉換了從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添加功能請求以支持此功能。
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.