asp.net mvc3 简单的文件上传下载

本文转自:http://www.cnblogs.com/kaixing/archive/2011/11/10/2244634.html

web.config配置

 

 <add name="连接字符串" connectionString="data source=服务器名;Initial Catalog=数据库;Persist Security Info=True;User ID=用户名;Password=密码" providerName="System.Data.SqlClient" />

 

建立数据库、表就省略了····

 

1.建立模型文件FileStores.cs

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.ComponentModel;

using System.ComponentModel.DataAnnotations;



namespace UpLoadFile.Models

{

    [Table("FileStore")]      //    关联表用

    public class FileStore

    {

        public int ID { get; set; }

        [DisplayName("文件类型")]

        public string MimeType { get; set; }

        [DisplayName("文件名")]

        public string FileName { get; set; }

        [DisplayName("文件路径")]

        public string FileUrl { get; set; }

    }

}

 

2.新建文件DbConnect.cs 建立数据库链接用

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Entity;

using System.ComponentModel;

using System.ComponentModel.DataAnnotations;



namespace UpLoadFile.Models

{

    public class DbConnect : DbContext

    {

        public DbConnect(string connecting) : base(connecting) { }



        public DbSet<FileStore> FileStores { get; set; }

    }

}

 

3.建立控制器UploadController.cs,以下是代码

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.IO;

using UpLoadFile.Models;



namespace UpLoadFile.Controllers

{

    public class UploadController : Controller

    {

        DbConnect db = new DbConnect("FileConnector");//数据库链接,FileConnector为web.config的链接字符串

        public ActionResult Index()

        {

            return View();

        }

 

   //文件上传

        public ActionResult Upload()

        {

            foreach (string upload in Request.Files)

            {

                if (!HasFiles.HasFile(Request.Files[upload])) continue;



                string miniType = Request.Files[upload].ContentType;

                Stream fileStream = Request.Files[upload].InputStream;

                string path = AppDomain.CurrentDomain.BaseDirectory + "files\\";

                string filename = Path.GetFileName(Request.Files[upload].FileName);

                Request.Files[upload].SaveAs(Path.Combine(path, filename));



                var files = new FileStore()

                {

                    MimeType = miniType,

                    FileName = filename,

                    FileUrl = Path.Combine(path, filename)

                };

                db.FileStores.Add(files);//存储到数据库

                db.SaveChanges();

            }

            return RedirectToAction("List");

        }

 

   //下载列表页

        public ActionResult List()

        {

            var list = db.FileStores.ToList();

            return View(list);

        }

 

   //文件下载

        public FilePathResult Download(int id)

        {

            var fileinfo = db.FileStores.Find(id);

            return File(fileinfo.FileUrl, fileinfo.MimeType, fileinfo.FileName);

        }

    }



    public static class HasFiles

    {

        public static bool HasFile(this HttpPostedFileBase file)

        {

            return (file != null && file.ContentLength > 0) ? true : false;

        }

    }



}

 

4.视图文件

 

index.cshtml

 

@model UpLoadFile.Models.FileStore

@{

    ViewBag.Title = "上传文件";

}



<h2>上传文件</h2>

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))

{

 

  //使用此控件会限制文件大小最大上传4m

 

    可在web.config中配置<httpRuntime 

            executionTimeout= "5400 " 

            maxRequestLength= "2048000 " 文件大小

             useFullyQualifiedRedirectUrl= "false " 

          /> 

    <div id="files">

    <input type="file" name="FileUpload" />

    </div>

    <input type="button" id="add" value="增加" />

    <input type="submit" name="Submit" id="Submit" value="上传" />

}

<script type="text/javascript">

    var n = 1;

    $("#add").click(function () {

        var filename = "FileUpload" + n;

        $("#files").append("<input type=\"file\" name=\""+filename+"\" />");

        n++;

    });

</script>

 

其他页面自己建立,

 

下载<a href="@Url.Action("Download", new { id=Model.ID})">@Model.FileName</a>

 

你可能感兴趣的:(asp.net)