[英]Javascript download document in browser. Web API
I'm using a Web API to fetch my document using the following: 我正在使用Web API通过以下方式获取我的文档:
[Route("Api/DocumentApi/DownloadDocument")]
[HttpGet]
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: 这是我认为是问题的我的Javascript GET:
DocumentToDownload = $(that).closest('.document-item').data('documentid');
var url = '/Api/DocumentApi/DownloadDocument';
var data = {
DocumentID: DocumentToDownload
};
$.ajax({
type: "GET",
url: url,
contentType: "application/json",
data: data,
dataType: "json",
success: function (json, status) {
if (status != "success") {
log("Error loading data");
return;
}
log("Data loaded!");
},
error: function (result, status, err) {
log("Error loading data");
return;
}
});
Im unsure what to put after: 我不确定该放什么:
success: function (json, status) {
Ajax file downloads are not allowed for security reasons (otherwise any site could download any file to the users machine in the background) 出于安全原因,不允许下载Ajax文件(否则任何站点都可以在后台将任何文件下载到用户计算机)
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. 无需使用ajax调用,如果
href
指向的URL看起来像您的API所执行的那样,则可以触发下载而无需使用普通链接重新加载页面,而无需使用普通链接。 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. 其中DocumentID设置为您要下载的文档的ID。 When the user clicks the link the page won't change/refresh
当用户单击链接时,页面将不会更改/刷新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.