简体   繁体   中英

HttpPostedFileBase File Content is deleted after using it once C# MVC

I am posting form data into a controller with a few values and an Excel file.

Then I do two things 1. send the file to the admin 2. Iterate through the rows and save the data.

The problem I am have is after sending the file the content of the file gets deleted and corrupted.

When I try to iterate through the rows and save the data first then the attachment in the email is corrupted.

Home Controller:

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

This is my email method

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

Why is the model.File.ContentLength property is 0 after sending the email?

I switched the order to save the data first then send the email and the most important thing is reseting the position of the stream after it was used content.Seek(0, SeekOrigin.Begin);

Here is the working Home Controller method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM