ASP.NET MVC3 实现多文件上传

本文介绍如何在ASP.NET MVC中实现多文件上传功能,并将文件信息及内容存储到数据库的过程。包括路由配置、模型类设计、控制器逻辑及视图展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 { getset; }
    
public String PersonName {setget; }
    
public String PersonImageType {setget; }
    
public String PersonImageFileName {setget; }
    
public int PersonImageSize {setget; }
    
public Byte[] PersonImage {setget; }

    
public string strCnString= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Image2Access.mdb";
    
public void LoadById(int id)
    {
      System.Data.OleDb.OleDbConnection myConnection 
=newSystem.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 
=newSystem.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 
=newSystem.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
)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值