【问题标题】:download file failed using response ASP.NET 5使用响应 ASP.NET 5 下载文件失败
【发布时间】:2022-01-18 10:14:58
【问题描述】:

我有以下代码来下载文件

jquery

 function DownloadExcel() {
        var laundrys = new Object();          

        $.ajax({
            type: 'POST',
            url: '@Url.Content("Laundry/DownloadExcel")',
            data: { laundry: laundrys},
            dataType: 'json',
            beforeSend: function () {
                $("#loadinggif").show();
            },
            success: function (result) {
                $("#loadinggif").hide();
                if (result.isuccess) {
                    GenerateFile(result);
                }
                else {
                    Swal.fire('Error Found', result.messageerror, 'error');
                }
            },
            error: function (result) {
                $("#loadinggif").hide();
                Swal.fire('Unknown Error', result, 'error');

            }
        });
    }

    function GenerateFile(result) {
        $.fileDownload('@Url.Content("Laundry/GenerateFiles")',
            {
                httpMethod: "POST",
                data: {
                    folder: result.folder,
                    filesname: result.filesname
                },
                successCallback: function (url) {
                    Swal.fire('Download Success', "", 'success');
                },
                failCallback: function (responseHtml, url) {
                    Swal.fire('Download Failed',responseHtml, 'error');
                }
            });
    }

这是我的 c# 中的代码 c#

public JsonResult DownloadExcel(Laundry laundry)
        {
            bool result = true;
            string MsgError = null;
            string Folder = null;
            string FileName = "GenerateFile-"+ DateTime.Now.ToString("yyyyMMdd_HHmmss").Replace("/", "-")+".xls";
            try
            {
                string startupPath = _webHostEnvironment.WebRootPath;
                Folder = startupPath + "\\template\\";
                string Path = Folder + "Template.xls";
                string NewPath = Folder + FileName;

                System.IO.File.Copy(Path, NewPath, true);

                HSSFWorkbook workBook;
                using (FileStream fs = new FileStream(NewPath, FileMode.Open, FileAccess.Read))
                {
                    workBook = new HSSFWorkbook(fs);
                }

               //mycode
              
                workBook.SetSheetName(0, "Report Laundry");
                using (FileStream fs = new FileStream(NewPath, FileMode.Create, FileAccess.Write))
                {
                    workBook.Write(fs);
                    fs.Close();
                }

            }
            catch(Exception e)
            {
                result = false;
                MsgError = "Error Exception: " + e.Message;
            }

            return Json(new { isuccess = result, messageerror = MsgError,folder = Folder, filesname = FileName,  });
        }

public ActionResult GenerateFiles(string folder, string filesname)
        {
            string Msg = "success";
            try
            {
                byte[] Data = System.IO.File.ReadAllBytes(folder + filesname);
                string contentType;
                new FileExtensionContentTypeProvider().TryGetContentType(filesname, out contentType);

                HttpContext.Response.Clear();
                HttpContext.Response.ContentType = contentType;
                HttpContext.Response.Headers.Add("Content-Length", Convert.ToString(Data.Length));
                HttpContext.Response.Headers.Add("Content-Disposition", string.Format("{0};FileName=\"{1}\"", "attachment", filesname));
                HttpContext.Response.Headers.Add("Set-Cookie", "fileDownload=true; path=/");
                HttpContext.Response.Body.WriteAsync(Data);
            }
            catch(Exception e)
            {
                Msg = "error Exception : "+e.Message;
            }

            System.IO.File.Delete(folder + filesname);

            return Json(Msg);
        }

当我使用以下代码时,下载成功但文件未下载并显示错误消息 failed network error。是不是我的响应码写错了?

【问题讨论】:

  • "下载成功,但文件没有下载" 这似乎是矛盾的。如果文件没有下载,那么如何下载成功?
  • 也许这与您在同一响应中同时发送文件内容 JSON 有效负载这一事实有关?
  • 如果我的声明的意思没有被理解,我很抱歉,我的意思是下载消息显示成功但文件没有下载。
  • @RichardDeeming 我已经编辑了我的代码,希望你能理解。对不起,如果我的英语不好
  • 正如我所说,您将在对GenerateFile 操作的响应中同时发送文件内容和 JSON blob。这会损坏文件。

标签: javascript jquery httpresponse asp.net5


【解决方案1】:

您的 GenerateFiles 方法试图在同一个响应中返回两件事 - 文件的内容和 JSON blob。那是行不通的。

您还应该删除folder 参数,因为它会带来安全风险。您没有对其进行验证,因此黑客可以指示您的方法从您服务器上的任何位置向他们发送 any 文件。并且您需要验证您返回的文件的完整路径是否在目标文件夹中。

public ActionResult GenerateFiles(string filesname)
{
    string startupPath = _webHostEnvironment.WebRootPath;
    string folder = System.IO.Path.Combine(startupPath, "template");
    string filePath = System.IO.Path.Combine(folder, filesname);
    
    if (!filePath.StartsWith(folder, StringComparison.OrdinalIgnoreCase))
    {
        // The file is not within the target folder.
        // Eg: The user requested "../../../../passwords";
        return NotFound();
    }
    
    if (!System.IO.File.Exists(filePath))
    {
        // The file does not exist.
        return NotFound();
    }
    
    if (!new FileExtensionContentTypeProvider().TryGetContentType(filesname, out string contentType))
    {
        // The file MIME type is not available.
        return NotFound();
    }
    
    string downloadFileName = System.IO.Path.GetFileName(filePath);
    byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
    System.IO.File.Delete(filePath);
    
    HttpContext.Response.Headers.Add("Set-Cookie", "fileDownload=true; path=/");
    return File(fileBytes, contentType, downloadFileName);
}

【讨论】:

  • 非常感谢,这很有帮助,祝您有美好的一天
猜你喜欢
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多