您的位置:首页 > 编程语言 > ASP

运用ASP.NET MVC实现的图片上传功能

2020-03-01 10:35 423 查看

全部代码经过本人调试,运行通过,适合用来做参考,稍微修改即可变成自己的案例:

 首先来建立数据库:

库名任意取

,表名这里叫Picture

字段名:

PictureID

FileContent

MimeType

FileName

[Content]

现在我们来看看Controller层代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using MvcApplication1.Models;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Xml.XPath;

public class PictureController : Controller
    {
        //
        // GET: /Picture/
        PictureDAL pal = new PictureDAL();
        public ActionResult Index()
        {
            Picture p = Session["userName"] as Picture;
            List<Picture> all = pal.BindPictureData(p.userID);
            ViewData["picture"] = all;
            return View(all);
        }

               
        /// <summary>
        /// 上传图片的处理功能
        /// </summary>
        /// <returns></returns>
        public ActionResult AddImages()
        {
            Picture p = new Picture();
            string content = Request.Form["txtImages"];
            foreach (string upload in Request.Files)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "/Views/Images";
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                Request.Files[upload].SaveAs(Path.Combine(path, filename));
            }

            //------------------------------------------------------------------------

            foreach (string upload in Request.Files)
            {
                string mimeType = Request.Files[upload].ContentType;
                Stream fileStream = Request.Files[upload].InputStream;
                string fileName = Path.GetFileName(Request.Files[upload].FileName);
                int fileLength = Request.Files[upload].ContentLength;
                byte[] fileData = new byte[fileLength];
                int userID =int.Parse( Session["userName"].ToString());
                fileStream.Read(fileData, 0, fileLength);
               
                int b = pal.InsertToPicture(fileData, mimeType, fileName, content,userID);
                if (b > 0)
                {
                    Response.Write("<script>alert('上传成功!');location.href='../Views/Picture/Index.aspx';</script>");
                   
                }
                else
                {
                    Response.Write("上传成功!");

                }
            }
            return RedirectToAction("Index");
        }
        /// <summary>
        /// 相册删除功能
        /// </summary>
        /// <returns></returns>
        public ActionResult Delete(int id)
        {
            Picture p = new Picture();
            p.PictureID = id;
            if (pal.DeletePicture(p.PictureID))
            {
                Response.Write("<script>alert('删除成功!');location.href='Index.aspx'</script>");
            }

            return RedirectToAction("Index");
        }
    }

接下来是数据访问Model层代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Model;
using System.Data.SqlClient;
namespace MvcApplication1.Models
{
    public class PictureDAL
    {
        PictureInfoDataContext plc = new PictureInfoDataContext("Data Source=.;Initial Catalog=MyBlog;Integrated Security=True");
        /// <summary>
        /// 绑定相册页面数据
        /// </summary>
        /// <returns></returns>
        public List<Picture> BindPictureData(int id)
        {
            List<Picture> all = new List<Picture>();
            var str = (from c in plc.Picture
                       where c.userID==id
                       select new
                       {
                            pictureID=c.PictureID,
                            pictureMimeType=c.MimeType,
                            pictureContent=c.FileContent,
                            pictureUrl = c.FileName,
                            content=c.Content,
                            userID=c.userID
                       }
                      ).ToList();
            for (int i = 0; i < str.Count; i++)
            {
                all.Add(new Picture { PictureID = str[i].pictureID, MimeType = str[i].pictureMimeType, FileName = str[i].pictureUrl, FileContent=str[i].pictureContent,Content=str[i].content, userID=str[i].userID });
            }
            return all;
        }
        /// <summary>
        /// 添加一条记录
        /// </summary>
        /// <returns></returns>
        public bool AddPicture(Picture p)
        {
            plc.Picture.InsertOnSubmit(p);
            plc.SubmitChanges();
            return true;
        }
        /// <summary>
        /// 照片上传功能
        /// </summary>
        /// <returns></returns>
        public int InsertToPicture(byte[] fileData,string mimeType,string fileName,string content,int userID)
        {
            string sql ="INSERT INTO Picture(FileContent, MimeType, FileName,Content,userID) VALUES (@FileContent, @MimeType, @FileName,@content,@userID)";
            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MyBlog;Integrated Security=True");
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@FileContent",fileData);
            cmd.Parameters.AddWithValue("@MimeType", mimeType);
            cmd.Parameters.AddWithValue("@FileName", fileName);
            cmd.Parameters.AddWithValue("@content", content);
            cmd.Parameters.AddWithValue("@userID",userID);
            int x = 0;
            try
            {
               conn.Open();
               x= cmd.ExecuteNonQuery();
            
            }
            catch
            { }
            finally
            {
                conn.Close();
            }
            return x;
        }
        /// <summary>
        /// 照片删除功能
        /// </summary>
        /// <returns></returns>
        public bool DeletePicture(int id)
        {
            var str=plc.Picture.SingleOrDefault(t=>t.PictureID==id);
            plc.Picture.DeleteOnSubmit(str);
            plc.SubmitChanges();
            return true;
        }

        public Picture ShowImage(string Name)
        {
            SqlDataReader rdr = null;
            string fileName= "", mimeType = "";
            byte[]  fileContent=null;
            Picture p=new Picture();
            p.FileContent=fileContent;
            p.MimeType=mimeType;
            p.FileName=fileName;
            using (var conn = new SqlConnection("Data Source=.;Initial Catalog=MyBlog;Integrated Security=True"))
            {
                var qry = "SELECT FileContent, MimeType, FileName FROM Picture WHERE FileName = @Name";
                var cmd = new SqlCommand(qry, conn);
                cmd.Parameters.AddWithValue("@Name", Name);
                conn.Open();
                rdr = cmd.ExecuteReader();
                if (rdr.HasRows)
                {
                    rdr.Read();
                    p.FileContent = (byte[])rdr["FileContent"];
                    p.MimeType = rdr["MimeType"].ToString();
                    p.FileName = rdr["FileName"].ToString();
                }
            }
            return p;

        }
      
      
    }
}

 

下面根据Controller层实现视图层的呈现,首先是Index视图页代码:

<body>
    <div>
    <%
        using (Html.BeginForm("AddImages", "Picture", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {%>
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     <input  type="text" name="txtImages" />
     <input type="file" name="FileUpload1" />&nbsp;&nbsp;&nbsp;&nbsp;
     <input type="submit" name="Submit" id="Submit" value="上传" /><br />
     &nbsp;<% }%><table width="100%" border="0" cellspacing="10" cellpadding="0">
                   <tr>
                <td height="50px"  colspan="2"  style="PADDING-LEFT: 20px; font-size:14px; text-align:center; FONT-WEIGHT: bold; COLOR: #ffffff; background-color:#3795d2;">
                    相册列表管理页</td>
            </tr>
                    <tr>
                      <td>
                        <table class="code" width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#BBD3EB">
                          <tr>
                            <td height="27" align="center" background="<%=ResolveUrl("../Images/index1_72.gif") %>" bgcolor="#FFFFFF">
                                操作</td>
                            <td height="27" align="center" background="<%=ResolveUrl("../Images/index1_72.gif") %>" bgcolor="#FFFFFF">
                                相片编号</td>
                            <td height="27" align="center" background="<%=ResolveUrl("../Images/index1_72.gif") %>" bgcolor="#FFFFFF">
                                相片描述</td>
                            <td height="27" align="center"
                                  background="<%=ResolveUrl("../Images/index1_72.gif") %>" bgcolor="#FFFFFF">相片</td>
                           
                          </tr>
                          <%foreach (Model.Picture gb in ViewData["picture"] as List<Model.Picture>)
                            { %>
                          <tr>
                            <td height="26" align="center" bgcolor="#FFFFFF">
                            <%=Html.ActionLink("修改", "Edit", new { id = gb.PictureID })%>&nbsp;
                            <%=Html.ActionLink("删除", "Delete", new { id = gb.PictureID })%>&nbsp;
                            </td>
                           
                            <td height="26" align="center" bgcolor="#FFFFFF"><%=gb.PictureID%></td>
                            <td align="center" bgcolor="#FFFFFF"> <%=gb.Content%></td>
                            <td align="center" bgcolor="#FFFFFF"> <%=gb.MimeType%><img style=" width:250px; height:180px;" src="/Views/Images/<%=gb.FileName%>"/></td>
                          </tr>
                          <%} %>
                          </table>
                      </td>
                    </tr>
                    <tr>
                      <td>&nbsp;<a href="Delete"><img src="<%=ResolveUrl("../Images/index1_84.gif") %>" width="74" height="31" border="0" /></a></td>
                    </tr>
                  </table>
              
    </div>
    
</body>

 

接下来是Delete.aspx页面代码和AddImages.aspx都没有写代码,但是你要建立这样两个页面,不然运行不成功,到此就建立完成整个图片上传和展示功能,下节继续为大家分享ASP.NET MVC的知识。

  • 点赞
  • 收藏
  • 分享
  • 文章举报
hzh_19870110 发布了2 篇原创文章 · 获赞 0 · 访问量 1万+ 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐