delete
delete

Reputation:

How do I save a file to disk?

Here is my controller:

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase excelFile)
    {

        /*Somewhere here, I have to save the uploaded file.*/

        var fileName = string.Format("{0}\\{1}", Directory.GetCurrentDirectory(), excelFile.FileName);
        var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);

        var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
        var ds = new DataSet();
        adapter.Fill(ds, "results");

        DataTable data = ds.Tables["results"];

        return View();
    }

Upvotes: 6

Views: 20354

Answers (3)

Tom Kris
Tom Kris

Reputation: 1227

Have you tried HttpPostedFileBase.SaveAs method?

Upvotes: 6

RQDQ
RQDQ

Reputation: 15579

[HttpPost]
public ActionResult Index(HttpPostedFileBase excelFile)
{
   /*Somewhere here, I have to save the uploaded file.*/

   var fileName = string.Format("{0}\\{1}", Directory.GetCurrentDirectory(), excelFile.FileName);

   excelFile.SaveAs(fileName );

   //...
}

When in doubt, look at the documentation: http://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.saveas.aspx

Upvotes: 4

Jack Marchetti
Jack Marchetti

Reputation: 15754

This is one way of handling it, if you're receiving uploaded files.

string nameAndLocation = "~/UploadedFiles/" + hpf.FileName;
hpf.SaveAs(Server.MapPath(nameAndLocation));

Upvotes: 12

Related Questions