How to download Document programmatically in SharePoint? - javascript

I wanted to have a link when user clicked, it allow user to download document from SharePoint Document Library.
The link will be placed inside an aspx page.
I tried the function below:
Response.ContentType = "application/xls";
Response.AppendHeader("Content-Disposition", "attachment; filename=abc.xls");
Response.TransmitFile(Server.MapPath("~/abc.xls"));
Response.End();
It allow me to download the document successfully, but the downloaded document cannot open.
what is the better way to do this?
Appreciate if you could provide me some references, thank you.

For your title, Javascript can get the contents of a web.config through an XMLHTTPRequest to the server, where the server is sending that file. Of course, that's a security risk and I can't think of any reason a person would want to do that.
As for you Excel file, I would suggest using a Content-Type of "application/octet-stream" for binary responses. The browser will then simply save the binary content under the specified file name and let the program (in this case, Excel) take care of interpretting it.

Related

Cannot download pdf from file-saver.js react

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.

How to make a link to download a server file on the browser?

I am trying to create a simple download link
The file I want to download is a .pdf that the user can upload, and now I want to make it possible to download. With the pop-up box, you know, or just on the chrome download bar
I've tried what every answer says:
Download PDF
But that leads to "Failed - no file", even though when I check
if(file_exists($GUIDELINES_PDF_DIR . $projectId . '.pdf'))
it returns true!
Some other notes:
I'm pretty shaky on server things, so maybe the same link doesn't work on PHP and on HTML? In that case, how can I find the file?
This link is within a <form>, so I don't really want to create another <form> inside it, or do anything that compromises the info that the user has inputed
Thank so much :)
$GUIDELINES_PDF_DIR is a directory on your server's hard disk.
The resulting path you are creating is relative to the root of your server's hard disk and not to the DocumentRoot of your web server.
You need to account for that difference when generating your URL.
Use a right headers:
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='downloaded.pdf'");

How to change filename when downloading file from server using javascript

I am downloading some images from facebook just for learning HTML and JS. But I don't want the filename to be some long string (contains some long string of numbers and chars ).
For eg I am using HTML5 download attribute
<a href="https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-xlt1/v/t1.0-9/12109181_503948273111743_2421725301227286538_n.jpg?oh=08c71f2236eaacc243ccd36475b4634e&oe=56BAA86C&__gda__=1459095933_f07fc4bb7bf54f48ac0b9286f8bc92c6"
download="imagename.jpg">
Download Image
</a>
Or this is JSFiddle of above code
When I click this link the file is download but with different name. My question is how do I change the filename something like images.jpg
Is it possible? If yes how should I go further.
The default filename is sent by the server through HTTP header:
Content-Disposition: attachment; filename='somefile'
Code that runs on the client has very limited control over files for security reasons. The only fix I can see is to have some server code which downloads the file from the other domain and then send it back with a new filename. So no, JS can't fix that for you.
I am relatively sure that the download attribute will only rename files that you are hosting, and not remote files.
You question is similar to this one:
Using download attribute with remote file
There is a workaround solution mentioned in that answer, but it's probably out of scope for just simple learning exercise.

HTML Object data URL from dynamic source

So all uploads for my app are not stored in my web server space, they are stored in a file system storage. When my users want access to the file they call a URL and the backend process will buffer the data to the browser via the HttpServletResponse outputstream. This works great as intended for downloading a file. Now my use-case has a scenario where I need to load an embedded object using this same method.
I am essentially loading a preview of the PDF file in the browser. This works fine if the PDF is stored on the web server and I provide a direct URL to the file. But when I use my method of sending files to the user then it doesn't work.
<object data='"+pdfUrl+"' type='application/pdf' width='160px' height='160px' />
If i put pdfURL into a browser my file gets downloaded no problem. So I think the issue is the HTTP headers I am sending in the outputstream that maybe is preventing the Object from loading properly. I am not sure if maybe its expecting something specific to be set in order to trigger loading the file
I am currently using very basic headers as follows:
BufferedInputStream is = <Some File Inputstream>;
resp.setContentType(new MimetypesFileTypeMap().getContentType(directory+filename));
resp.setHeader("Content-Disposition", "attachment; filename="+StringFormatHelper.formatFileName(filename));
bufferedCopy(is, resp.getOutputStream());
is.close();
resp.getOutputStream().flush();
Anyone have any ideas on what I have to change to get the data to properly load in the Object tag? I don't get any errors in the JS console or server side. I am not sure how to debug this issue.
Edit:
SO i just realized that if i right click on where the blank Object tag is at I have the option to "Save as..." and when I do I download the PDF. So the pdf data is loaded but Its just not displaying in the UI.
The issue is this line of code
resp.setContentType(new MimetypesFileTypeMap().getContentType(directory+filename));
This was not setting the correct mime-type for the file as I thought it was. So there was a mismatch in that the Object tag was looking for application/pdf but the server was sending a different MIME type in the header. Once I matched them up everything worked.
I was able to get the correct MIME type using the Spring provided lookup instead of the JDK lookup
new ConfigurableMimeFileTypeMap().getContentType(directory+filename)

How does a javascript download link work?

I've been using the Microsoft Technet site and you can download the ISO files by clicking a link on the page. The element is like this:
<a href="javascript:void(0)" onmouseout="HideToolTip()"
onmouseover="ShowToolTip(event,'Click here to download.')"
onclick="javascript:RunDownload('39010^313^164',event)"
class="detailsLink">Download</a>
I wasn't able to find the RunDownload() method in the scripts. And I wondered what it is likely to do. I mean usually when I provide a link for someone to download I provide an anchor to it:
download
But this is working differently what is the script doing? Because even when I ran 'Fiddler' I wasn't able to see the actual download location.
there's no such thing as a "javascript download" link. Javascript can open a new window, or simulate a click on a link.
What you have to find is which url the function triggered by this click will lead to.
here's an example of how to do it:
Suppose we have a:
<a id="download">download Here ยงยงยง</a>
then this jQuery code:
$('#download').click( function() {
window.location.href = 'http://example.org/download/ISO.ISO';
} );
will redirect to the URL http://example.org/download/ISO.ISO. Whether this url starts a download or not depends on HTTP headers and your browser, not on what javascript do.
Download location can be a url-rewritten path. This mean that maybe some parameters are given with HTTP Post and some HTTP handler in the Web server or web application may be getting some arguments from the HTTP request and write file bytes to an HTTP response, which absolutely hides where the file is located in the actual server's file system.
Maybe this is what's behind the scenes and prevents you to know the file location.
For example, we can have this:
http://mypage.com/downloads/1223893893
And you requested an executable like "whatever.exe" for downloading it to your hard disk. Where's the "http:/mypage.com/downloads/whatever.exe"? Actually, it doesn't exist. It's a byte array saved in a long database in some record, and "mypage" web application handles a request for a file that's identified as "1223893893" which can be a combination of an identifier, date time or whichever argument.
What I think the function RunDownload might do is that it might inform the server using get request to the server that another download is about to happen , or it might need to run the download background by setting the target attribute to an iframe so the user won't need to open another tab and download the file on the same page.
Download
JS
var runDownload=function(){
e.preventDefault();
increaseDownloadCountOnTheServer(location);
window.location.href="filelocation.exe";
}

Categories