使用响应 ASP.NET Core 下载文件失败

问题描述 投票:0回答:1

我有以下代码来下载文件

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);
        }

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

javascript jquery asp.net-core httpresponse
1个回答
0
投票

您的

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.