logo

ASP.NET MVC3 实现多文件上传

作者:孟宪会 阅读:2711 发表于:2011-09-08 15:32:50

1,首先,注册路由,采用微软提供的默认方法即可

Global.asax 代码
public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute(
"{resource}.axd/{*pathInfo}");

  routes.MapRoute(
      
"只是名称而已,随便写", // 路由名称
      "{controller}/{action}/{id}", // 带有参数的 URL
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
  );  

}

2,创建UploadFile对象。注意:这里只是一个例子,你还可以使用其他ORM工具生成

UpLoadFile.cs 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
  
public class UpLoadFile
  {
    
public int PersonId { get; set; }
    
public String PersonName { set; get; }
    
public String PersonImageType { set; get; }
    
public String PersonImageFileName { set; get; }
    
public int PersonImageSize { set; get; }
    
public Byte[] PersonImage { set; get; }

    
public string strCnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Image2Access.mdb";
    
public void LoadById(int id)
    {
      System.Data.OleDb.OleDbConnection myConnection
= new System.Data.OleDb.OleDbConnection(strCnString);
      String strSql
= "select * from [Person] Where PersonId=@PersonId";
      System.Data.OleDb.OleDbCommand command
= new System.Data.OleDb.OleDbCommand(strSql, myConnection);
      command.Parameters.AddWithValue(
"@PersonId", id);
      
//打开连接,执行查询
      myConnection.Open();
      System.Data.OleDb.OleDbDataReader dr
= command.ExecuteReader();
      
if (dr.Read())
      {
        
this.PersonImage = (Byte[])dr["PersonImage"];
        
this.PersonImageType = dr["PersonImageType"] as String;
      }
      myConnection.Close();
    }

    
public void SaveToDataBase()
    {
      System.Data.OleDb.OleDbConnection myConnection
= new System.Data.OleDb.OleDbConnection(strCnString);
      String strSql
= "INSERT INTO Person (PersonName,PersonImageType,PersonImageFileName,PersonImageSize,PersonImage)" +
                      
"VALUES (@PersonName,@PersonImageType,@PersonImageFileName,@PersonImageSize,@PersonImage)";
      System.Data.OleDb.OleDbCommand command
= new System.Data.OleDb.OleDbCommand(strSql, myConnection);
      command.Parameters.AddWithValue(
"@PersonName", this.PersonImageFileName);
      command.Parameters.AddWithValue(
"@PersonImageType", this.PersonImageType);
      command.Parameters.AddWithValue(
"@PersonImageFileName", this.PersonImageFileName);
      command.Parameters.AddWithValue(
"@PersonImageSize", this.PersonImageSize);
      command.Parameters.AddWithValue(
"@PersonImage", this.PersonImage);
      myConnection.Open();
      command.ExecuteNonQuery();
      myConnection.Close();
    }

    
public List<UpLoadFile> List()
    {
      List
<UpLoadFile> p = new List<UpLoadFile>();
      System.Data.OleDb.OleDbConnection myConnection
= new System.Data.OleDb.OleDbConnection(strCnString);
      String strSql
= "select * from [Person] Order By PersonID DESC";
      System.Data.OleDb.OleDbCommand command
= new System.Data.OleDb.OleDbCommand(strSql, myConnection);
      myConnection.Open();
      System.Data.OleDb.OleDbDataReader dr
= command.ExecuteReader();
      
while (dr.Read())
      {
        p.Add(
new UpLoadFile
        {
          PersonId
= Convert.ToInt32(dr["PersonId"]),
          PersonName
= Convert.ToString(dr["PersonName"]),
          PersonImageType
= Convert.ToString(dr["PersonImageType"]),
          PersonImageFileName
= Convert.ToString(dr["PersonImageFileName"]),
          PersonImageSize
= Convert.ToInt32(dr["PersonImageSize"]),
          PersonImage
= dr["PersonImage"] as Byte[]
        });
      }
      myConnection.Close();
      
return p;
    }
  }
}

3,编写控制器代码

HomeController.cs 代码

/// <summary>
/// 显示文件列表
/// </summary>
/// <returns></returns>
public ViewResult List()
{
  UpLoadFile f
= new UpLoadFile();
  List
<UpLoadFile> list = f.List();
  ViewBag.list
= list;
  
return View("Upload");
}
  
/// <summary>
/// 接收文件,并保存到数据库中的方法
/// </summary>
/// <returns></returns>
public ViewResult Upload()
{
  
for (int i = 0; i < Request.Files.Count; i++)
  {
    HttpPostedFileBase file
= Request.Files[i];
    
//存入文件
    if (file.ContentLength > 0)
    {
      file.SaveAs(Server.MapPath(
"~/") + System.IO.Path.GetFileName(file.FileName));
    }

    
//存入数据库
    if (file.ContentLength > 0)
    {
      
//得到文件数组
      byte[] fileData = new Byte[file.ContentLength];
      file.InputStream.Position
= 0; //此句很关键
      file.InputStream.Read(fileData, 0, file.ContentLength);
      
//得到文件大小
      int fileLength = file.ContentLength;
      
//得到文件名字
      string fileName = System.IO.Path.GetFileName(file.FileName);

      
//得到文件类型
      string fileType = file.ContentType;

      
//自定义文件对象
      UpLoadFile f = new UpLoadFile();
      f.PersonImage
= fileData;
      f.PersonName
= fileName;
      f.PersonImageType
= fileType;
      f.PersonImageSize
= fileLength;
      f.PersonImageFileName
= fileName;
      f.SaveToDataBase();        
    }
  }
  
return View(List());
}
    
/// <summary>
/// 显示图片
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public FileContentResult Display(int id)
{
  UpLoadFile f
= new UpLoadFile();
  f.LoadById(id);
  
return new FileContentResult(f.PersonImage, f.PersonImageType);
}

4,视图文件,显示列表和上传表单

Upload.cshtml 代码
<!DOCTYPE html>
<html>
<head>
  
<title>多文件上传</title>
</head>
<body>
  
<h2>多文件上传</h2>
  
<table border="1">
  
<thead>
  
<th>文件名</th>
  
<th>文件类型</th>
  
<th>浏览</th>
  
</thead>
  @
* 对于列表显示页面,进行特殊的处理,如果没有记录,则不显示列表。 *@
  @if (ViewBag.list
!= null)
  {    
    
<tbody>
      @for (
int i = 0; i < ViewBag.list.Count; i++)
      {
        
<tr>
      
<td>@ViewBag.list[i].PersonName</td>
      
<td>@ViewBag.list[i].PersonImageType</td>
      
<td><img alt="@ViewBag.list[i].PersonName" src='@Url.Action("Display", "Home", new { id = ViewBag.list[i].PersonId })' /></td>
        
</tr>
      }
    
</tbody>
  }  
  
</table>
  
<form action="/Home/Upload" enctype="multipart/form-data" method="post">
  
<input type="file" name="f1" /><br />
  
<input type="file" name="f2" /><br />
  
<input type="submit" value="多文件上传" />
  
</form>
</body>
</html>

  创建表格的语句(SQL Server)

SQL 代码
CREATE TABLE [dbo].[Person] (
[PersonID] int NOT NULL,
[PersonName] nvarchar(255),
[PersonImageFileName] nvarchar(255),
[PersonImageSize] int,
[PersonImageType] nvarchar(255),
[PersonImage] image
)

 

 创建表格的SQL语句(Access代码)

SQL 代码
CREATE TABLE [Person] (
[PersonID] integer primary key,
[PersonName] varchar(255),
[PersonImageFileName] varchar(255),
[PersonImageSize] integer,
[PersonImageType] varchar(255),
[PersonImage] OLEObject
)