首先,需要引用DBHelper辅助类,便于实现SQL语句的增删改差以及连接到数据库。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Reflection;
using System.Net;
using System.Net.Sockets;
namespace MVC.Controllers
{
public class DBHelper
{
private SqlConnection conn = null;
/// <summary>
/// 构造函数
/// </summary>
public DBHelper()
{
if (conn == null)
{
conn = new SqlConnection("这边是一个数据库连接字符串");
}
}
/// <summary>
/// 返回DataTable查询结果
/// </summary>
/// <param name="sql"></param>
/// <param name="par"></param>
/// <returns></returns>
public DataTable GetTable(string sql, SqlParameter[] par = null)
{
try
{
SqlCommand com = new SqlCommand(sql, conn);
if (par != null)
{
com.Parameters.AddRange(par);
}
SqlDataAdapter ada = new SqlDataAdapter(com);
DataTable dt = new DataTable();
ada.Fill(dt);
ada.Dispose();
if (conn.State == ConnectionState.Open)
{
this.Close();
}
return dt;
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
this.Close();
}
throw;
}
}
/// <summary>
/// 返回List查询结果
/// </summary>
/// <param name="sql"></param>
/// <param name="par"></param>
/// <returns></returns>
public List<T> GetToList<T>(string sql, SqlParameter[] par = null)
{
List<T> li = DataTableToList<T>(GetTable(sql));
return li;
}
/// <summary>
/// 返回查询结果首行首列
/// </summary>
/// <param name="sql"></param>
/// <param name="par"></param>
/// <returns></returns>
public object ExecuteScalar(string sql, SqlParameter[] par = null)
{
try
{
this.Open();
SqlCommand com = new SqlCommand(sql, conn);
if (par != null)
{
com.Parameters.AddRange(par);
}
return com.ExecuteScalar();
}
catch (Exception ex)
{
this.Close();
throw;
}
}
/// <summary>
/// 返回执行结果受影响行数
/// </summary>
/// <param name="sql"></param>
/// <param name="par"></param>
/// <returns></returns>
public int ExecuteNonQuery(string sql, SqlParameter[] par = null)
{
try
{
this.Open();
SqlCommand com = new SqlCommand(sql,conn);
if (par != null)
{
com.Parameters.AddRange(par);
}
return com.ExecuteNonQuery();
}
catch (Exception ex)
{
this.Close();
throw;
}
}
/// <summary>
/// Table转list集合
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private static List<T> DataTableToList<T>(DataTable dt)
{
//初始化值
List<T> result = new List<T>();
for (int i = 0; i < dt.Rows.Count; i++)
{
T _t = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] propertys = _t.GetType().GetProperties();
foreach (PropertyInfo pro in propertys)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (pro.Name.Equals(dt.Columns[j].ColumnName))
{
if (dt.Rows[i][j] != DBNull.Value)
{
pro.SetValue(_t, dt.Rows[i][j], null);
}
else
{
pro.SetValue(_t, null, null);
}
break;
}
}
}
result.Add(_t);
}
return result;
}
/// <summary>
/// 打开数据库链接
/// </summary>
private void Open()
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
}
/// <summary>
/// 关闭数据库链接
/// </summary>
private void Close()
{
if (conn.State != ConnectionState.Closed)
{
conn.Dispose();
}
}
}
}
其次,控制器。
在次不在多说,代码都有注释。
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using MVC.Models; namespace MVC.Controllers { public class FilterController : Controller { //==========================================================物理路径上传和下载======================================================== //实例化DBHelper DBHelper db = new DBHelper(); //显示数据 // GET: Filter public ActionResult Index() { string sql = $"select * from WenJian"; var list=db.GetToList<WenJian>(sql); return View(list); } //上传文件1 [HttpPost] public void Upload1() { //获取要上传的文件名称及类型 var fils = HttpContext.Request.Files[0]; //文件名称分割成 名称和类型 var temp = fils.FileName.Split('.'); //获取物理路径 文件名称 var fname = fils.FileName; //获取类型 var extendName = temp[temp.Length - 1]; //设置储存路径 var path = HttpContext.Server.MapPath("~/Filters/"); //如果没有此路径 if(!Directory.Exists(path)) { //创建路径 Directory.CreateDirectory(path); } //获取到时间格式的名称 var name = DateTime.Now.ToFileTime() +"."+ extendName; fils.SaveAs(Path.Combine(path,name)); //添加到数据库 string sql = $"insert into WenJian values('{fname}','{path+name}')"; //返回结果 var result=db.ExecuteNonQuery(sql); if(result>0) { Response.Write("<script>alert('上传成功');location.href='/Filter/index'</script>"); } else { Response.Write("<script>alert('上传失败');location.href='/Filter/index'</script>"); } } //下载文件1 [HttpGet] public FileStreamResult DownLoad1(string FileName) { ////由虚拟路径转换为物理路径 //string filePath = Server.MapPath(string.Format("~/{0}/{1}", "Filters",FileName)); FileStream fs = new FileStream(FileName, FileMode.Open); return File(fs, "text/plain", FileName); } } }
最后,前台页面
@model IEnumerable<MVC.Models.WenJian> @{ ViewBag.Title = "Index"; } <h2>上传文件和下载文件</h2> @*==========================================================物理路径上传和下载========================================================*@ <h4>物理路径上传和下载</h4> <form action="/Filter/Upload1" method="post" enctype="multipart/form-data" class="table-bordered"> <input type="file" name="fils" /> <input type="submit" value="上传文件" /> </form> <form action="/Filter/DownLoad1" method="get" enctype="multipart/form-data" class="table-bordered"> <table class="table table-bordered" style="text-align:center;border:1px solid red"> <tr> <td>编号</td> <td>原文件名称</td> <td>下载</td> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(m => item.Id) </td> <td> @Html.DisplayFor(m => item.Name) </td> <td> <a href="@Url.Action("DownLoad1","Filter",new { FileName=item.Paths})">下载</a> </td> </tr> } </table> </form> @*==========================================================以上是物理路径上传和下载========================================================*@ <br />