简体   繁体   English

浏览器中的Javascript下载文件。 网络API

[英]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.

相关问题 “浏览器”的区别。 和“信使”。 使用 webextension/javascript API 时 - Difference of the "Browser." and "Messenger." when using a webextension/javascript API Javascript检测浏览器。 表达式不起作用 - Javascript detecting browser. Expressions not working Javascript,基于浏览器显示图像。 - Javascript, Display image based on browser. 如何使用网页浏览器下载api? - How to use web browser download api? 如何处理重定向请求以响应浏览器上的下载文件。 - How to handle redirect request in react to download file on browser. 使用 javascript 在 Web 浏览器中签署 XML 文档 - Sign XML document in web browser using javascript 从客户端 Web 浏览器与串行端口通信。 - Communicate with the serial port from client web browser. 用于浏览器的Google API密钥。 引荐来源网址设置时出现的问题 - Google API Key for browser. Issue when referrers set 我正在尝试导入Typescript文件,但是当我将其编译为Javascript时,我遇到的问题来自Web浏览器的错误。 出口没有定义 - I'm trying to import Typescript files but when I compile it to Javascript I'm getting bad Errors from the web browser. exports is not defined 如何让Web浏览器下载存储在JavaScript String中的文件? - How to get a web browser to download a file that is stored in a JavaScript String?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM