views:

16

answers:

2

I'm trying to put together a page whereby a user can upload a file, and it goes to a database.

I'm following a tutorial, and my controller method so far looks like this:

public ActionResult Index()
{
    ViewData["Message"] = "File Upload";
    foreach (string upload in Request.Files)
    {
        if (!Request.Files[upload].HasFile()) continue;
        string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
        string filename = Path.GetFileName(Request.Files[upload].FileName);
        Request.Files[upload].SaveAs(Path.Combine(path, filename));
    }

    return View();
}

Here is also an example of what my view looks like:

<p>
    <% using (Html.BeginForm("", "home", FormMethod.Post, new { enctype = "multipart/form-data" }))
       { %>
    <input type="file" name="FileUpload1" /><br />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
    <% } %>
</p>

I'm currently getting two compile errors however:

  1. 'System.Web.HttpPostedFileBase' does not contain a definition for 'HasFile' and no extension method 'HasFile' accepting a first argument of type 'System.Web.HttpPostedFileBase' could be found (are you missing a using directive or an assembly reference?)
  2. The name 'Path' does not exist in the current context

Here is also an example of what I'm using for namespaces in the controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;

I'd be very grateful if anyone could point me in the right direction to fixing this error.

+3  A: 

I think I found the tutorial you were following?

If so - check the part where the author has written a custom extension method for the HasFile() method. It's not part of the framework, so you would need to create that also.

The second issue is that Path is part of the System.IO namespace, so you would need to add that too.

AndyB
Thanks a lot AndyB!
TaraWalsh
A: 

I am a bit curious about how one could skip the file saving thing to the server and just directly (stream) put it into a table.

Jens

Jens