在asp.net mvc3中上传文件

时间:2014-08-01 12:18:19

标签: asp.net-mvc

我目前正在使用我的asp.net MVC3(aspx语法)项目的Entity Framework Code First方法。

我的项目中有一个名为EmployeeModel

的模型
public class EmployeeModel
{
    public string imageinfo;
    public string fileinfo;
}

我的DbContext是

public  class ContextDB:DbContext
{
     public DbSet<EmployeeModel> Employee { get; set; }
}

我希望在我的视图中有fileinfo and imageinfo的文件浏览器来上传文件和图像,文件和图像的路径需要存储在数据库中。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

Asp.Net MVC我们必须使用HttpPostedFileBase上传文件,如下所示: -

控制器:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
 if (file != null)  // file here will have your posted file which you post from view
 {
    int byteCount = file.ContentLength;   <---Your file Size or Length
    byte[] yourfile = new byte[file.ContentLength];
    file.InputStream.Read(yourfile , 0, file.ContentLength);
    var doc1 = System.Text.UnicodeEncoding.Default.GetString(empfile);
    // now doc1 will have your image in string format and you can save it to database.
 }
}

查看:

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
 <input type="file" name="file" />
 <input type="submit" value="OK" />
}

答案 1 :(得分:0)

尝试使用

.chtml

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

控制器

public class HomeController : Controller
{
    // This action renders the form
    public ActionResult Index()
    {
        return View();
    }

    // This action handles the form POST and the upload
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // extract only the fielname
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");        
    }
}