I need to download the pdf/word/excel file from external server in to my ionic application. Sample code below
const fileTransfer: FileTransferObject = this.transfer.create();
const url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
console.log("error : " +error);
});
I need to store all the files in my application itself not an external storage or an internal storage. Would this be possible?
By the way if we keep on store the files in the application itself then there is any application performance issue came?
Thanks
AK
Related
I have small problem while developing react, spring boot application dashboard.
Here is my problem, I developed file upload dashboard it's requests from client (react) to
backend server side (springboot) by axios call multipart-form.
Seem there is no problem on
uploading file to server (because uploaded file opens well inside of server and the file
size is equal).
However, when I downloading the file the file size increases and cannot
open properly (It's shows alarm that the file damaged).
Now I don't know where to find the solution :( plz help me.
here is my react code which has axios call with file name:
function fileDownlod(props) {
api.responseType = 'blob'
api.defaults.headers.common[`Authorization`] = 'Bearer ' + localStorage.getItem('token')
api
.post('/filedown', { uuid: props }, header)
.then((response) => {
const name = response.headers['content-disposition'].split('fileName=')[1]
console.log(response.headers)
console.log(name)
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', name)
link.style.cssText = 'display:none'
document.body.appendChild(link)
link.click()
link.remove()
})
and this is my spring boot code (where I checked that the file size both equal)
#CrossOrigin(value = {"*"})
#RequestMapping(value = "/filedown", method= {RequestMethod.POST, RequestMethod.GET})
public void fileDown (#RequestBody FileEntity param, HttpServletResponse response) throws Exception {
String fileFullPath = fileLocation + param.getUuid();
try{
Path filePath = Paths.get(fileFullPath);
FileEntity fileEntity = fileRepository.findByUuid(param.getUuid());
if(fileEntity.getContentType().contains("image")){
response.setContentType("multipart/form-data");
}else{
response.setContentType("application/octet-stream");
}
response.setHeader("Content-Disposition", "attachment; fileName=" + URLEncoder.encode(fileEntity.getFileName(),"UTF-8"));
response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader( "Access-Control-Allow-Headers","Content-Disposition");
response.setHeader( "Access-Control-Expose-Headers","Content-Disposition");
byte[] fileByte = FileUtils.readFileToByteArray(new File(fileFullPath));
System.out.println("file size of fileByte: " + fileByte.length);
System.out.println("file size of file inf. from DB: " + fileEntity.getFileSize());
response.getOutputStream().write(fileByte);
response.getOutputStream().flush();
response.getOutputStream().close();
For more information, I'm develeping in macOS and when I deploy the application file download won't work in iphone eihter :( Any suggestion? thank you.
I found my answer by myself the problem was "api.responseType = 'blob'" which didn't work as responseType.
this was my solution below
api
.post('/filedown', { uuid: props }, { responseType: 'blob' }, header)
In storage it creates a hierarchy of folders, the same is in the path of the image, inside these folders it creates the image file, but when I download this image it does not open.
const finalizarAlbum = () => {
let albumNumber = Date.now();
let username = email.split('#')[0] + '_' + albumNumber;
let pathImage =
'file:///data/user/0/com.master/cache/tm-rn-image-crop-picker/8f403c24-c538-43f4-bb8d-e6c83be46a36.jpg';
firebase
.storage()
.ref()
.child('imagens')
.putString(pathImage)
.on(
'state_changed',
snapshot => {
let pct = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
},
error => {
alert(error.code);
},
() => {}
);
};
Since your code calls putString() it is writing the string "file:///data/user/0/com.master/cache/tm-rn-image-crop-picker/8f403c24-c538-43f4-bb8d-e6c83be46a36.jpg" to Cloud Storage, not the contents of the file that the string refers to.
To upload the actual contents of the file, you'll want to call the putFile() method (if you're using react-native-firebase, or the put method with a File or Blob reference (if you're using the regular JavaScript SDK.
I'm building an Ionic app using the Ionic Native File plugin. I need the app to be able to read a file that I've saved in the app itself, but I don't understand where I need to store the file. The official Cordova documentation says something about a certain cordova.file.dataDirectory, whereas the Ionic documentation uses this example:
import { File } from '#ionic-native/file';
constructor(private file: File) { }
...
this.file.checkDir(this.file.dataDirectory, 'mydir').then( //stuff).catch( //stuff);
I don't understand where I need to put my file so that the app can read them.
Do not use file:///android_asset/
You can store the file in file.dataDirectory
Storing the file
I am using http to download a zip. I then unzip and delete the zipped file afterwards.
const down = this.http.downloadFile(uri, {}, {}, path + 'data.zip')
.then(data => {
console.log(data.status);
console.log("DOWNLOAD SUCCESS");
this.desc = "Extracting";
this.loading = 100;
this.downloading = false;
this.zip.unzip(path + 'data.zip', path, (this.UnzipProgress))
.then((result) => {
if(result === 0) this.file.removeFile(path,'data.zip');
if(result === -1) console.log('UNZIP FAILED');
});
})
.catch(error => {
console.log("ERROR::");
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
Retrieving the file
The only thing that worked for me was convertFileSrc()
let win: any = window;
let safeURL = win.Ionic.WebView.convertFileSrc(this.file.dataDirectory+'data/yourFile.png');
Hope this helps
I am using the ionic 2 framework and the cordova file plugin.
I am downloading a pdf file from a server, using the php readfile($path) method, on the client side, i am using Http from angular/http.
Now the problem is, that after the download and a save using the writeFile(path, file,data,options) method from ionic-native/file, the content of the file is not the same as the content from the server.
Notice: Left the output file and right the server version, both printed with the cat command.
I have no idea why the content is not the same.
The http call:
this.http.post(httpEndpoint + ":8280/download", data, headers).subscribe(response => {
me.proceedFile(response.text(), file, fileManager, opener);
});
Here the save:
private proceedFile(data:string, file:File, fileManager:FileManger,
opener:FileOpener) {
...
const me = this;
const putFile = function () {
fileManager.writeFile(fileManager.dataDirectory ,"data/" +
strid+"/" + file.name, data, true).then(_ => {
});
};
...
}
Regards Liz3
I am working on ionic project which needs to work offline. My issue is, how to save uploaded image offline in sqlite database, and when track any wifi connection, synch to online.
Image uploading online is working fine, using cordova camera plugin and filetransfer plugin.
You can use cordova file plugin's copyfile method to store the image locally, and then save its link in the database for further use. When the wifi is detected, just use that link to upload file to server with same cordovafile plugin.
$cordovaCamera.getPicture(options).then(function(sourcePath) { //for capturing image
console.log(sourcePath);
var sourceDirectory = sourcePath.substring(0, sourcePath.lastIndexOf('/') + 1); //image file with path url
var sourceFileName = sourcePath.substring(sourcePath.lastIndexOf('/') + 1, sourcePath.length); //image name
console.log("Copying from : " + sourceDirectory + sourceFileName);
console.log("Copying to : " + cordova.file.dataDirectory + sourceFileName);
//used to store file locally
$cordovaFile.copyFile(sourceDirectory, sourceFileName,
cordova.file.dataDirectory, sourceFileName).then(function(success) {
$scope.fileName = cordova.file.dataDirectory + sourceFileName;
console.log($scope.fileName, success);
$scope.propic = $scope.fileName;
}, function(error) {
console.log(error);
});
}, function(err) {
console.log(err);
});