在浏览器中下载Javascript文档.Web API

Javascript download document in browser. Web API

本文关键字:文档 Web API Javascript 下载 浏览器      更新时间:2023-09-26

我使用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) {

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

不需要使用ajax调用,如果href指向一个返回文档(头是文档)的URL,您可以触发下载,而无需使用正常链接重新加载页面,这看起来像您的API正在做的。所以你可以简单地输入:

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

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