【问题标题】:Javascript download document in browser. Web API浏览器中的 Javascript 下载文档。网络 API
【发布时间】:2017-01-02 01:58:03
【问题描述】:

我正在使用 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;            
    }

这看起来像是在检索文档。但是,我希望文档立即下载或显示一个弹出窗口供用户选择保存文件的位置,但这种情况不会发生。立即下载是首选。

这是我认为是问题所在的 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;
                    }
                });

我不知道该放什么:

 success: function (json, status) {

【问题讨论】:

    标签: javascript json ajax asp.net-web-api


    【解决方案1】:

    出于安全原因,不允许下载 Ajax 文件(否则任何站点都可以在后台将任何文件下载到用户计算机)

    无需使用 ajax 调用,如果 href 指向返回文档(标题是文档)的 URL,您可以触发下载而无需使用普通链接重新加载页面,它看起来像您的API 正在做。所以你可以简单地这样做:

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

    其中 DocumentID 设置为您要下载的文档的 ID。当用户点击链接时,页面不会改变/刷新

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多