首页 > 解决方案 > HttpPostedFileBase 文件内容在使用一次后被删除 C# MVC

问题描述

我将表单数据发布到带有一些值和 Excel 文件的控制器中。

然后我做两件事 1. 将文件发送给管理员 2. 遍历行并保存数据。

我遇到的问题是在发送文件后文件的内容被删除和损坏。

当我尝试遍历行并首先保存数据时,电子邮件中的附件已损坏。

家庭控制器:

[HttpPost]
public ActionResult Index(ImportExcelViewModel model)
{                       
    try
    {
        var user = (User)Session[Utils.USER_SESSION];

        if (model.File != null)                
            MailClient.SendConfirmationEmailToAdminDataCollector(ApplicationName, FirstName, LastName, model.File, "Report.xlsx");
                   
        bool didErrorOccur = false;

        var _tempList = GetDataTableFromSpreadsheet(model.File.InputStream, false, out didErrorOccur);
    
        if (didErrorOccur)                                    
            return Json(new { success = false, excel = true, message = errors.ToString() });

        var list = ExcelRepository.Save(model, _tempList);

        MailClient.SendConfirmationEmailToUserDataCollector(user.Email, user.FirstName, user.LastName);                                         

        return Json(new { success = true, message = "success" });
    }
    catch(Exception e)
    {
        return Json(new { success = false, excel = false, message = e.Message });
    }
}

这是我的电子邮件方法

public static void SendConfirmationEmailToAdminDataCollector(string ApplicationName, string fname, string lname, HttpPostedFileBase document, string documentName)
{
        string strSmtpServer = smtp_server;
        string strSmtpPickup = smtp_pickup_location;
        int intPort = smtp_port;
        MailMessage objMail = new MailMessage();

        string email_to = !string.IsNullOrEmpty(enviroment) && enviroment == "dev" ? email_to_test : email_admin;           

        objMail.From = new MailAddress(email_from);
        MailClient.AddAddress(email_to, ADD_EMAIL_TO, ref objMail);
        MailClient.AddAddress(email_bcc, ADD_EMAIL_BCC, ref objMail);

        objMail.Subject = "New Submission From " + ApplicationName;
        objMail.Body =  "<p>A new submission was entered by " + fname + " " + lname + ".</p>" +
                        "<p>Thank You</p>";
        
        objMail.Attachments.Add(new Attachment(document.InputStream, documentName));
        objMail.IsBodyHtml = true;

        try
        {
            MailClient.sendMail(strSmtpServer, intPort, strSmtpPickup, objMail);
        }
        catch
        {
            throw new Exception("could not send a confirmation email");
        }
}

为什么发送邮件后model.File.ContentLength 属性为0?

标签: c#asp.net-mvc

解决方案


我切换顺序先保存数据然后发送电子邮件,最重要的是在使用后重置流的位置content.Seek(0, SeekOrigin.Begin);

这是有效的 Home Controller 方法:

[HttpPost]
public ActionResult Index(ImportExcelViewModel model)
{                       
    try
    {
        var user = (User)Session[Utils.USER_SESSION];                
        var content = model.File.InputStream;                              

        bool didErrorOccur = false;

        var _tempList = GetDataTableFromSpreadsheet(content, false, out didErrorOccur);
    
        if (didErrorOccur)                                    
            return Json(new { success = false, excel = true, message = errors.ToString() });

        model.UserID = user.ID;

        content.Seek(0, SeekOrigin.Begin);

        var newEntry = DataCollectorRepository.Save(model, _tempList);

        content.Seek(0, SeekOrigin.Begin);

        if (newEntry != null)
        {
            string file_name = model.ApplicationName + ".xlsx";
                        MailClient.SendConfirmationEmailToAdminDataCollector(model.ApplicationName, user.FirstName, user.LastName, content, file_name);
            MailClient.SendConfirmationEmailToUserDataCollector(user.Email, user.FirstName, user.LastName);
        }
        else
            return Json(new { success = false, excel = false, message = "Something went wrong saving your submission." });
    

        return Json(new { success = true, message = "success" });
    }
    catch(Exception e)
    {
        return Json(new { success = false, excel = false, message = e.Message });
    }
}

推荐阅读