I use flutter_downloader in app to allow downloading pdf files .
It is working well in Android,but in IOS,the notification of starting downloading the file doesn't appear although the file downloaded in the device.
I followed all instructions like described from Enable background mode,Add sqlite library,Configure AppDelegate
code:
final status = await Permission.storage.request();
if (status.isGranted) {
// Directory _path = await getExternalStorageDirectory();
// String _localPath = _path.absolute.path + Platform.pathSeparator + 'ESPRS_Docs';
var savedDir;
if (Platform.isIOS) {
savedDir = await getApplicationDocumentsDirectory();
} else {
savedDir = Directory('/storage/emulated/0/Download');
// Put file in global download folder, if for an unknown reason it didn't exist, we fallback
// ignore: avoid_slow_async_io
if (!await savedDir.exists()) savedDir = await getExternalStorageDirectory();
}
String random_no =randomAlphaNumeric(6) ;
var split_name=p_title.replaceAll(" ","-");
await FlutterDownloader.enqueue(
url: p_link,
savedDir: savedDir.path,
fileName: "${split_name}-${random_no}.pdf",
showNotification: true,
saveInPublicStorage: true,
openFileFromNotification: true,
headers: {"auth": "Downloader"},
);
}else {
print("Permission deined");
};
Notification messages of download progress are only shown for Android. Behaviour differs between platforms.
final taskId = await FlutterDownloader.enqueue(
url: 'your download link',
savedDir: 'the path of directory where you want to save downloaded files',
showNotification: true, // show download progress in status bar (for Android)
openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);
Related
Im trying to download using Expo-File-System on an expo project with react native.
The download option works on Expo-Go during testing but wont work when i push it in production mode.
It says that it is "unable to save file in the local URI because you dont have Document Permissions" as shown in the Picture below.
Here is the code (Using typescript):
import * as MediaLibrary from 'expo-media-library';
///For downloading the file
const download = async (item: ICurriculumCourseDocument) => {
setIsloading(true)
await FileSystem.downloadAsync(
`https:/baseUrl`,
FileSystem.documentDirectory + item.filename,
options
)
.then(({ uri }) => {
setIsloading(false)
console.log('Finished downloading to', uri);
onShareIOS(uri)
})
.catch(error => {
setIsloading(false)
alert(error);
});
}
//For sharing the file using the Share
const onShareIOS = async (uri: string) => {
const imageFileExts = ['jpg', 'png', 'gif', 'heic', 'webp', 'bmp'];
if (imageFileExts.every(x => !uri.endsWith(x))) {
const UTI = 'public.item';
await Sharing.shareAsync(uri, {UTI});
}
};
Here is the full Alert with the error message:
I am using this code and it works fine in simulator as I am getting a location and can get pdf file from there
async createPDF() {
let options = {
html: '<h1>PDF TEST</h1>',
fileName: 'test',
directory: 'Documents',
};
let file = await RNHTMLtoPDF.convert(options)
// console.log(file.filePath);
alert(file.filePath);
}
But the above code problem in the real iOS mobile as it is saving the pdf file somewhere. I don’t know where but I am not able to see that file in my mobile. So can anyone tell me how can I save my file in the downloads or documents in the iOS . So that I can see the downloaded file.
Found the answer to convert file in base64 string
You can solve this issue by using base64 as the following:
let options = {
html:
`
<h2 style="text-align: center">${'Some text and dynamic value'}</h2>
`,
fileName: 'TestingPDF',
directory: 'Documents',
base64: true
};
let file = await RNHTMLtoPDF.convert(options);
You shoud use 'react-native-file-access' to copy the file and move it to Downloads directory, so let's install it by: npm i react-native-file-access --save
Lets copy the file to the Downloads directory by the following:
const fileName = 'PMA_CurrentBalanceFile.pdf'; //whatever you want to call your file
const filePath = `${Dirs.DocumentDir}/${fileName}`;
const base64Data = file.base64; //our base64 encode file which done by RNHTMLtoPDF;
Then write the following code to do your job:
if (Platform.OS === 'android') {
const permissionGranted = await permissionWriteExternalStorage();
if (permissionGranted) {
await FileSystem.writeFile(filePath, base64Data, 'base64');
if (!FileSystem.exists(filePath)) return;// check to see if our filePath was created
await FileSystem.cpExternal(filePath, fileName,'downloads');// copies our file to the downloads folder/directory
// file should now be visible in the downloads folder
ToastAndroid.show("", "One File Downloaded", ToastAndroid.SHORT);
}
return;
}
if (Platform.OS === 'ios') {
// IOS version
await FileSystem.writeFile(filePath, base64Data, 'base64');
Alert.alert('', 'One File Downloaded');
}
I have a deeplinking configuration setup to open a specific page when a URL is clicked on the device. This is working fine when the app is open in the background, but if the app is closed, it just opens the app and does not navigate.
Here is my linking configuration:
const linking = {
prefixes: ["appname://"],
config: deepLinkRouting,
getStateFromPath(path:string, options:any) {
//build custom params
},
async getInitialURL() {
// Check if app was opened from a deep link
const url = await Linking.getInitialURL();
if (url != null) {
return url;
}
},
subscribe(listener) {
const onReceiveURL = ({ url }) => listener(url);
Linking.addEventListener('url', onReceiveURL);
return () => {
// Clean up the event listener
Linking.removeEventListener('url', onReceiveURL);
};
},
}
This linking object is provided as a prop to my <NavigationContainer/>
I am testing this on simulator with the npx uri-scheme open command. I notice when you close the app and reopen it, the app is rebuilt, so I'm wondering if this invalidates testing. Any help is appreciated!
I am at the Point where i call the Flutter Camera package, take a photo and save it temporary in my app using pathProvider. Now i want so upload this image to an api using the Dio package. My pathprovider is able to give me a String with the Path to the image. With this path i am able to display the Image using the Image widget from Flutter. however i am not able to send it to an api.
processImage(file) async {
print(file);
// /var/mobile/Containers/Data/Application/7915E945-4582-4586-8062-F73537283283/Library/Caches/2019-07-22 13:35:36.243335.png
var newfile = File(file);
Dio dio = new Dio();
FormData formData =
new FormData.from({"size": "auto", "image_file": newfile});
try {
final response = await dio.post(
"YYYYYYYYYYYY",
data: formData,
options: Options(
headers: {'X-Api-Key': 'XXXXXXX'},
),
onSendProgress: (int sent, int total) {
print("send $sent / $total");
},
onReceiveProgress: (int sent, int total) {
print("receive $sent / $total");
},
);
} on DioError catch (e) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx and is also not 304.
print(e);
}
// print(response);
}
The Dio library that has a class called UploadFileInfo which you can use for your case:
FormData formData =
new FormData.from({
"size": "auto",
"image_file": UploadFileInfo(newfile, "file_name.txt")},
);
I implemented a Jersey REST service to download the zip file.
Now, I would like to use axios in front end to download the zip file.
Everything is fine in PC Chrome but when tried with Safari on iPad it opens a tab with name "unknown".
I have searched some articles and mentioned that this may related to IOS safari compatibility.
e.g. https://caniuse.com/#feat=download
However, I also want know if there is any method to show the downloaded file as "file.zip" for safari.
Below is my code
Backend:
#GET
#Path("/getTestingReport")
#Produces("application/zip")
public Response getTestingReport() throws Exception {
// set file (and path) to be download
File file = new File("C:/Users/abc/Desktop/test.zip");
ResponseBuilder responseBuilder = Response.ok((Object) file);
responseBuilder.header("Content-Disposition", "attachment; filename=\"MyJerseyZipFile.zip\"");
return responseBuilder.build();
}
Frontend:
axios.get("report/getTestingReport").then((response) => {
console.log("response", response)
var blob = new Blob([response.data], { type: "application/zip" });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.zip');
document.body.appendChild(link);
link.click();
}).catch((error) => {
console.error("error response", error.response)
});
May I have any suggestion?