javascript 如何通过xmlHttpRequest从Json下载文件

lokaqttq  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(128)

我想通过xmlHttpRequest从Json接收文件,但下载后无法打开所需文件。

存储在数据库中的所需文件没有问题,因为当我将其保存在C#中时,它会打开它,问题仅在于无法正确接收所需文件的java脚本部分。
Java脚本:

var xmlHttpRequest = new XMLHttpRequest();
if (!window.XMLHttpRequest) {
   xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

let formData = new FormData();
formData.append('request.Id', window.$(this).attr('data'));
xmlHttpRequest.open("POST", 'Url', true);

xmlHttpRequest.onloadend = function () {
        let response = ParseJson(xmlHttpRequest.responseText);

        alert(response.Result);

        let blob = new Blob([response.File], { type: response.MimeType }); 

        let a = document.createElement('a');
        a.href = window.URL.createObjectURL(blob);

        a.download = response.FileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(a.href);
}
xmlHttpRequest.send(formData);

控制器:

public IActionResult GetFileDownload(GetFileDownloadRequest request)
{
       //Get byte[] from database

       return Json(new GetFileDownload()
       {
              Result = "OK",
              FileName = file.Name ?? "",
              MimeType = Path.GetExtension(file.Name).GetMimeType(),
              File = file.File
       });
}
jtjikinw

jtjikinw1#

JSON响应的首字母将变为小写而不是大写。所以它将是response.mimeTyperesponse.fileresponse.fileName。您可以尝试以下代码进行测试
GetFileDownload.cs

public class GetFileDownload
    {
        public string Result { get; set; }
        public string FileName { get; set; }
        public string MimeType { get; set; }
        public byte[] File { get;set; }
    }

控制器

[HttpGet("DownloadFile")]
        public IActionResult DownloadFile()
        {
            var path = Path.Combine("E:\\Sample.xlsx"); 
            byte[] bytes = System.IO.File.ReadAllBytes(path); //get bytes

            var contentType = "";
            new FileExtensionContentTypeProvider().TryGetContentType(path, out contentType);

            var result = new GetFileDownload()
            {
                Result = "OK",
                FileName = "Sample.xlsx",
                MimeType = contentType,
                File = bytes
            };
            return result == null ? NotFound() : Ok(result);
        }

脚本

<script>
    const xhr = new XMLHttpRequest();   
    xhr.open('GET', 'https://localhost:7011/api/values/downloadfile',true) 
    xhr.onloadend = function () {
        if (this.status == 200) {
            let response = JSON.parse(this.response);
            console.log(response);
            let blob = new Blob([response.file], { type: response.mimeType }); 
            let a = document.createElement('a');
            a.href = window.URL.createObjectURL(blob);
            a.download = response.fileName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(a.href);
        }
    }
    xhr.send();
</script>

F12

相关问题