There is an Angular 6 app having a feature to download pdf files. It uses REST API from another Spring Boot application to download files.
The requirement is that i need to open pdf file in new tab and while saving it shall have a meaningful name.
I am able to get the file downloaded and open in new tab too. But while saving the file, it takes name from the url.
I tried by opening the file directly from REST API in browser and save it as well as getting blob and open in new window from angular app. Both open the files but while saving they take name from URL.
Angular - Open blob in new window
blob:https://defg.com/89a0396e-994b-43d0-b3e3-aaa95d47db9f
If i try to download opened file, it suggests to save with name
89a0396e-994b-43d0-b3e3-aaa95d47db9f.pdf
Is there a way to pass or set filename in below approach?
var fileURL = window.URL.createObjectURL(file);
window.open(fileURL, "_blank");
API - Takes Encrypted name
https://abcd.com/ws/fileDownload/85C1E5010AFAE309E89534FAC594C9110D74FED4DF78AAA8EE199C78B570FABF8BC6640F0563778DD963
If i try to download opened file, it suggests to save with correct name for first time, shows string from url as name from second attempt, 85C1E5010AFAE309E89534FAC594C9110D74FED4DF78AAA8EE199C78B570FABF8BC6640F0563778DD963.pdf
Inspected response, headers look good,
Content-Disposition: inline; filename= "test.pdf"
Any suggestions would be helpful. Thanks in advance.
You could use file-saver library as follow:
import { saveAs } from 'file-saver';
...
awesomeDownloader(url: string, fileName: string) {
const blobFile = functionsThatGetsTheBlob(url);
saveAs(blobFile, fileName);
}
...
Related
I am trying to download the pdf from this url :
http://www.africau.edu/images/default/sample.pdf
I followed the example and wrote the code below.
import { saveAs } from "file-saver";
const downloadPDF = ()=>{
var FileSaver = require("file-saver");
FileSaver.saveAs(
"http://www.africau.edu/images/default/sample.pdf",
"somehthing.pdf"
);
}
However, when the downloadPDF function is invoked on the button pressed. The file is not being saved. The pdf is simply being opened in the new tab.
The screenshot of what the pdf looks like in the new tab is shown below.
How do I save the pdf file?
Also, is this approach to get the pdf even valid in the first place or is axios.get() more preferred approach to get the file, then save the response file (response.body) via FileSaver.saveAs()
If the question is unclear, please let me know in the comment before flagging - I will make the necessary update. Thank you
seems like the FileSaver does not help.
However if the file is coming from the server we recommend you to first try to use Content-Disposition attachment response header as it has more cross-browser compatiblity.
as far as I know, there are 2 ways to download file in browser.
server returns a response with header Content-Disposition with value attachment or header Content-Type with value application/octet-stream. Browser will promote the SaveDialog and handle this download for you. This is preferred way to download but this requires you to have control over the server.
you just use ajax or axios to get the data of any file at anywhere. then you create a dummy link to download (like this one). then browser will promote for SaveDialog and then save file to disk. This is just fine for small file but not for large files because you have to store entire file in memory before saving it to local disk.
I think option 2 is appropriate for you.
Example here. In this example, I place a file named abc.json in public folder. Note that the server must enable cors for your website origin. otherwise, there's no way for you to access that file in javascript code.
I have a mobile app that wraps around the web-app, using webview.
The web-app has a button to open a large .zip file (e.g. 100 MB).
The user clicks a button, and selects a .zip file.
This triggers an onChange function with a variable of type File (Blob), which includes attributes like:
file name
file size
file type (application/zip)
The javascript code then parses the .zip file, extracts specific data within it and uses it within the web-app.
This works well within the web-app, when the app is called via the Chrome browser.
For example when operated in chrome browser on an Android phone, I can pull the .zip file and open it in the web-app.
I want to do the same but using the mobile app.
I am able to pick up the .zip file using a File Chooser, and pass it to Webview but I have problems to fetch the file from the Javascript code.
For reference, I am able to pass an image, by creating a data_uri using stringBuilder and passing the content (as data:image/jpeg;base64).
But the zip file is much larger.
When calling fetch(fileUri) from the Javascript side I'm getting errors.
I'm using the following uri
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
The fetch succeeds but returns a blob with size of 165 (i.e. not the actual size of the file) which hosts the error message:
{
"error": "Not Found",
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
}
The program flow is like so:
I select a .zip file via FileChooser.
In onActivityResult, the uri value is /document/msf:12858 (seen via uri = intent.getData();)
The uri needs to be mapped into a real path file url, such that the fileUrl will be passed to webview.
Webview will then fetch the file using the fileUrl.
I searched how to get the real path file url when selecting a file with FileChooser, and found
this, and this links.
I wasn't able to get the real file path, so I decided to read the file and write it to another location, so I can get a file path. (this is not efficient and done just to check the functionality).
I create the new file using the following code:
InputStream stream = context.getContentResolver().openInputStream(uri);
File file2 = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "file2.zip");
writeBytesToFile(stream, file2);
I don't see any errors when creating the file, and when creating the file, the number of bytes that are read and written to the new file are as expected.
For file2, I get a value of:
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
Then, within the Javascript code I fetch this file path.
But I'm getting a Blob with the "file-not-found" content as above.
So:
How can I verify that the file is indeed created and that the path can be fetched from webview?
How can I get the real file path of the original selected file, so I don't have to read and write the original file to new location just to get the file path?
Thanks
I was able to get the file from external storage by doing the following steps:
create an initial uri (uri1)
The uri is created by:
creating a temporary file (file1) in the storage dir via
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
I'm not sure why a temporary file need to be created but if I don't create a file I cannot get the uri.
createFile3
get the uri via
Uri uri1 = FileProvider.getUriForFile(context, "com.example.android.fileprovider", file1);
create an intent with the following attributes:
Intent.ACTION_OPEN_DOCUMENT
category: Intent.CATEGORY_OPENABLE
type: "application/zip"
extra attribute: fileIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri1);
this opens a dialog box for selecting openable zip files in the Downloads directory,
after the file is selected, a new uri (uri2) is created that includes the name of the selected file.
extract the name of the file via
String fileName = getFileName(context, uri2);
create the dirPath by appending the filename
dirPath = "/data/user/0/com.example/" + fileName;
if the dirPath does not exist (first time), write the file to its dirPath location.
on successive ocassions dirPath exists, so there is no need to re-write the file.
open the file with regular Java means, e.g. via
ZipFile zip = new ZipFile(dirPath);
i used this method to download file without show file path in browser tab it's working on docx and pdf file but when i click on image link then it's show the actual path of image which one i don't want so can you help me out this please?
function downloadfile12(file)
{
var baseurl = jQuery("#baseurl").val();
var valFileDownloadPath = baseurl + 'assets/uploads/files/'+file;
window.open(valFileDownloadPath , 'Download');
}
If you want to download an image file in a new tab,you need to add a header Content-Disposition: attachment; filename="filename.jpg" on server side to tell your browser to download the image rather than render it in new tab.
If you just want to download the image file,try download
I currently have a desktop App built with Node Webkit. When the user is online, the App will open up PDF files from the server. I then save these files locally so they are available when offline.
I am using the Node.js File System's fs.writeFile(), to save the PDF locally but when trying to open it via the App the PDF is blank. When I try to open it direct from the folder I get the below error.
Can anyone please advise?
//save PDF file for offline
function saveFile(pdfvar) {
var filename = 'test.pdf';
fs.writeFile(filename, pdfvar);
}
//open PDF in new window
$('#stage').on('click', '#pdflink', function(event){
var pdfvar = (this.getAttribute('data-pdffile'));
window.open(pdfvar, "_blank");
if(online===true){
saveFile(pdfvar);
}
});
Are you holding entire content of a PDF in a DOM element attribute this.getAttribute('data-pdffile') ? This is where it may get corrupted.
When you call
window.open(pdfvar, "_blank");
the content is not ready to be opened like that. It should be first converted to base64 encoded url.
window.open('data:application/pdf,' + escape(pdfvar));
UPDATE:
The actual problem was that the OP was trying to save the file using it's URL in "pdfvar"
fs.writeFile(filename, pdfvar);
but the file created was containing only a URL itself. What was required was downloading the file first using a http library:
How to download a file with Node.js (without using third-party libraries)?
I am building an windows app using Tide SDK. How can I open a local file from my app. For example, I have a pdf file somewhere in my harddisk. I put the link to that file to my app. When I click on the link, I want it to open the pdf file using default programm associated with pdf type file.
If it is not possible then I have one more general question. Is it possible to access local file system by any app that built using html5 and javascript?
we can access local file system in tidesdk application.
See the following code.
var contents;
var file= 'test.txt';
var Dir = Ti.Filesystem.getUserDirectory();
var readfi= Ti.Filesystem.getFile(Dir, file);
if (readfi.exists())
{
var Stream = Ti.Filesystem.getFileStream(readFi);
Stream.open(Ti.Filesystem.MODE_READ);
contents =Stream.read();
alert( contents );
Stream.close();
}
The above code will read the text file and alert the content. Visit here to know tidesdk file system.
Following code will open the given URL in default browser.
Ti.Platform.openURL('http://stackoverflow.com');
Following code will Open the given application or file in the system's default program.
Ti.Platform.openApplication('C:/Documents and Settings/Thavamani00/Desktop/readme.txt');
Ti.Platform.openApplication('C:/Documents and Settings/Thavamani00/Desktop/cart15.png');
The above code displays the text file in notepad and displays the image in mircosoft picture manager.
it works well for me.i hope its your required answer.