Shaun Morehammered Denovan Shaun Morehammered Denovan - 4 years ago 104
JSON Question

Javascript download document in browser. Web API

I'm using a Web API to fetch my document using the following:

public IHttpActionResult DownloadDocument(int documentID)
Document documentToDownload = new Document();

using (TrustInvestmentSwitchEntities db = new TrustInvestmentSwitchEntities())
DocumentRepository repo = new DocumentRepository();
documentToDownload = repo.GetSingle(db, x => x.ID == documentID);

var stream = new MemoryStream();
var result = new HttpResponseMessage(HttpStatusCode.OK)
Content = new ByteArrayContent(stream.GetBuffer())
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
FileName = documentToDownload.FileName
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var response = ResponseMessage(result);
return response;

This looks like its working at retrieves the document. However, I want the document to either download immediately or show a popup for the user to select a location to save the file and this is not happening. Download immediately is preferred.

Here is my Javascript GET which I think is the problem:

DocumentToDownload = $(that).closest('.document-item').data('documentid');
var url = '/Api/DocumentApi/DownloadDocument';
var data = {
DocumentID: DocumentToDownload
type: "GET",
url: url,
contentType: "application/json",
data: data,
dataType: "json",
success: function (json, status) {
if (status != "success") {
log("Error loading data");
log("Data loaded!");
error: function (result, status, err) {
log("Error loading data");

Im unsure what to put after:

success: function (json, status) {

Answer Source

Ajax file downloads are not allowed for security reasons (otherwise any site could download any file to the users machine in the background)

No need to use an ajax call, you can trigger the download without reloading the page using a normal link if the href is pointing to a URL that returns a document (the header is a document) which it looks like your API is doing. So you could simply do:

 <a href="/Api/DocumentApi/DownloadDocument?DocumentID=10">Download</a>

Where the DocumentID is set to the ID of the document you want to download. When the user clicks the link the page won't change/refresh

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download