如何返回文件以及错误消息以进行查看? [英] How to return a file along with a error message to view?

查看:119
本文介绍了如何返回文件以及错误消息以进行查看?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是asp.net-mvc的新手,现在我正在尝试返回一个excel文件,并在用户单击按钮时返回错误消息(如果返回的文件缺少列).我使用return File()返回我的文件以进行查看,但是我不知道如何一起发送错误消息. (我曾尝试过ViewBag,但没有用)如何将文件和错误消息发送回查看?

I am new to asp.net-mvc and right now I'm working on returning a excel file along with an error message if the returning file has column missing, when the user clicked the button. I use return File()to return my file to view, but I don't know how to send the error message together. (I'd tried ViewBag but it didn't work) How to send a file back to view along with an error message?

推荐答案

我认为您可以尝试使用Ajax将excel文件生成到服务器中的temp文件夹,然后通过ajax响应下载该文件,其原始代码如下所示下方:

I think you can try to use Ajax for generate the excel file to a temp folder in server, and download it by the ajax response, the fronend code will like below:

$.blockUI({ message: '<h3><img src="@Url.Content("~/Content/images/busy.gif")" /> Please wait a moment...</h3>' });    
$.ajax({
        type: "POST",
        url: '@Url.Action("ExportExcel","YourController")',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    }).done(function (data) {
        //console.log(data.result);
        $.unblockUI();
        if (data.fileName != "") {
            window.location.href = "@Url.RouteUrl(new { Controller = "YourController", Action = "Download"})/?file=" + data.fileName;
        }
    });

在控制器中:

[HttpPost]
public JsonResult ExportExcel()
{
    DataTable dt = DataService.GetData();
    var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
    string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);

    using (var exportData = new MemoryStream())
    {
        Utility.WriteDataTableToExcel(dt, ".xls", exportData);

        FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
        exportData.WriteTo(file);
        file.Close();
    }

    var errorMessage = "you can return the errors in here!";

    return Json(new { fileName = fileName, errorMessage = "" });
}

和下载动作

[HttpGet]
[DeleteFileAttribute]
public virtual ActionResult Download(string file)
{
    string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
    return File(fullPath, "application/vnd.ms-excel", file);
}

在这里,我创建了一个删除过滤器,用于下载后自动删除文件:

in here, I created a delete filter for auto delete the file after download:

/// <summary>
/// The Action filter for delete the file after downloaded
/// </summary>
public class DeleteFileAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Flush();
        string filePath = (filterContext.Result as FilePathResult).FileName;
        System.IO.File.Delete(filePath);
    }
}

这篇关于如何返回文件以及错误消息以进行查看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆