首页 > 解决方案 > 无法将文件从控制器操作发送到浏览器进行下载

问题描述

我正在向 a 发送 a XMLHttpRequestMVC Controller因此我希望收到一个文件。使用浏览器进行调试时,我得到了一个没问题的response结果,但我不知道为什么它不是一个文件:

JS

 window.submit=function () {
                return new Promise((resolve, reject) => {
                    var form = document.getElementById("newTestForm");
                    var data = new FormData(form);
                    var xhr = new XMLHttpRequest();


                    var method = form.getAttribute('method');
                    var action = form.getAttribute('action');
                    xhr.open(method, action);
                    xhr.onload = function () {
                        if (this.status >= 200 && this.status < 300) {
                            resolve(xhr.response); //response looks ok...but no file starts downloading
                        }
                        else if (xhr.status != 200) {
                            reject("Failed to submit form with status" + xhr.status);
                        }
                    }
                    xhr.send(data);
                });
            }

控制器

    [HttpPost]
    [Route([Some Route])]
    public  async Task  BenchAsync(object request)
    {
        try
        {
            string fileName = "results.txt";

            object result = await service.RunAsync(request);
            byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result)); 
            this.Response.ContentType = "application/octet-stream";
            this.Response.ContentLength = data.Length;

            using(MemoryStream stream=new MemoryStream(data))
            {
                await stream.CopyToAsync(this.Response.Body);
            }
        }
        catch (Exception ex)
        {
            throw;

        }
    }

标签: javascript.net-coredownloadxmlhttprequest

解决方案


多亏了这篇文章,我已经解决了

看来我必须将响应转换为BLOB,创建一个下载链接并将其指向此 blob 和创建的链接才能下载文件。

所以函数看起来像:

 window.submit= function () {
        return new Promise((resolve, reject) => {
            var form = document.getElementById("newTestForm");
            var data = new FormData(form);
            var xhr = new XMLHttpRequest();


            var method = form.getAttribute('method');
            var action = form.getAttribute('action');
            xhr.open(method, action);
            xhr.onload = function () {
                if (this.status >= 200 && this.status < 300) {
                    var blob = new Blob([this.response], { type: 'image/pdf' });

                    let a = document.createElement("a");
                    a.style = "display: none";
                    document.body.appendChild(a);

                    let url = window.URL.createObjectURL(blob);
                    a.href = url;
                    a.download = 'mytext.txt';

                    a.click();

                    window.URL.revokeObjectURL(url);
                }
                else if (xhr.status != 200) {
                    reject("Failed to submit form with status" + xhr.status);
                }
            }
            xhr.send(data);
        });
    }

PS我不知道 blob 的类型是什么,txt但如果扩展名正确,它也可以工作。


推荐阅读