衫裤跑路 2020-03-08 21:35 采纳率: 50%
浏览 68

为什么只下载txt文件?

我正在尝试在ASP.NETWebAPI中下载文件。如果我尝试.xsl.pdf.docx...等格式文件,即使下载了也是无序的文件,但是txt格式的没有任何问题。这是我的API代码:

        public HttpResponseMessage GetFile(DownloadInput input)
    {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        var fileNm = input.fiName;
        string filePath = (@"C:\Uploads\" + input.folderName + @"\" + fileNm);
        if (!File.Exists(filePath))
            {
                response.StatusCode = HttpStatusCode.NotFound;
                response.ReasonPhrase = string.Format("File not found: {0} .", fileNm);
                throw new HttpResponseException(response);
            }
            byte[] bytes = File.ReadAllBytes(filePath);
            response.Content = new ByteArrayContent(bytes);
            response.Content.Headers.ContentLength = bytes.LongLength;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = fileNm;    
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(filePath));
            return response;
    }

我的ajax代码:

        function DownloadFile(fiName,foName) {
        var UserData = {
            "folderName":  "" + foName+ "",
            "fiName":  "" + fiName + "",
        };
        var userDataJson = JSON.stringify(UserData);
        $.ajax({
            url: "http://localhost:9000/api/Calendar/GetFile",
            type: "POST",
            contentType: "application/json",
            data: userDataJson,
            success: function (response, xhr, request) {
                let contentType = request.getResponseHeader('Content-Type');
                let blob = new Blob([response], {
                    type: contentType
                });
                let link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = ad;
                link.click();
            },
            error: function (err) {
                console.log(JSON.stringify(err));
            }
        });
多谢!
  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-10-30 05:59
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算