c#图片上传和显示的实现方法

时间:2022-05-13 10:33:00

由于需要图片上传的功能,所以花了一些时间网上找相关资料终于搞定,效果图如下:

c#图片上传和显示的实现方法

下面的是解决方案截图和上传的图片截图:

c#图片上传和显示的实现方法

c#图片上传和显示的实现方法

具体实现代码如下:

1.界面代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="c#" autoeventwireup="true" codebehind="uploadpic.aspx.cs" inherits="pic_try.uploadpic" %>
 
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>图片上传和显示</title>
  <style type="text/css">
  .pic_text{ color:red;}
  .pic_label { color:gray; margin-top:5px; margin-bottom:5px;}
  .pic_image { margin:5px;}
  </style>
</head>
<body>
  <form id="form1" runat="server">
  <div class="pic_image"><asp:image id="pic" runat="server" /></div>
  <div><asp:fileupload id="pic_upload" runat="server" /><asp:label id="lbl_pic" runat="server" class="pic_text"></asp:label></div>
  <div class="pic_label">上传图片格式为.jpg, .gif, .bmp,.png,图片大小不得超过8m</div>
  <div><asp:button id="btn_upload" runat="server" text="上传" onclick="btn_upload_click"/></div>
  </form>
 
</body>
</html>

2.后台代码uploadpic.aspx.cs

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.io;
using system.security.cryptography;
using system.web.security;
 
namespace pic_try
{
  public partial class uploadpic : system.web.ui.page
  {
    protected void page_load(object sender, eventargs e)
    {
 
    }
 
    protected void btn_upload_click(object sender, eventargs e)
    {
      boolean fileok = false;
      if (pic_upload.hasfile)//验证是否包含文件
      {
        //取得文件的扩展名,并转换成小写
        string fileextension = path.getextension(pic_upload.filename).tolower();
        //验证上传文件是否图片格式
        fileok = isimage(fileextension);
 
        if (fileok)
        {
          //对上传文件的大小进行检测,限定文件最大不超过8m
          if (pic_upload.postedfile.contentlength < 8192000)
          {
            string filepath = "/images/";
            if (directory.exists(server.mappath(filepath)) == false)//如果不存在就创建file文件夹
            {
              directory.createdirectory(server.mappath(filepath));
            }
            string virpath = filepath + createpasswordhash(pic_upload.filename, 4) + fileextension;//这是存到服务器上的虚拟路径
            string mappath = server.mappath(virpath);//转换成服务器上的物理路径
            pic_upload.postedfile.saveas(mappath);//保存图片
            //显示图片
            pic.imageurl = virpath;
            //清空提示
            lbl_pic.text = "";
          }
          else {
            pic.imageurl = "";
            lbl_pic.text = "文件大小超出8m!请重新选择!";
          }
        }
        else {
          pic.imageurl = "";
          lbl_pic.text = "要上传的文件类型不对!请重新选择!";
        }
      }
      else
      {
        pic.imageurl = "";
        lbl_pic.text = "请选择要上传的图片!";
      }
    }
 
    /// <summary>
    /// 验证是否指定的图片格式
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public bool isimage(string str) {
      bool isimage = false;
      string thestr = str.tolower();
      //限定只能上传jpg和gif图片
      string[] allowextension = { ".jpg", ".gif", ".bmp",".png" };
      //对上传的文件的类型进行一个个匹对
      for (int i = 0; i < allowextension.length; i++)
      {
        if (thestr == allowextension[i])
        {
          isimage = true;
          break;
        }
      }
      return isimage;
    }
 
    /// <summary>
    /// 创建一个指定长度的随机salt值
    /// </summary>
    public string createsalt(int saltlenght)
    {
      //生成一个加密的随机数
      rngcryptoserviceprovider rng = new rngcryptoserviceprovider();
      byte[] buff = new byte[saltlenght];
      rng.getbytes(buff);
      //返回一个base64随机数的字符串
      return convert.tobase64string(buff);
    }
 
    
    /// <summary>
    /// 返回加密后的字符串
    /// </summary>
    public string createpasswordhash(string pwd, int saltlenght)
    {
      string strsalt = createsalt(saltlenght);
      //把密码和salt连起来
      string saltandpwd = string.concat(pwd, strsalt);
      //对密码进行哈希
      string hashenpwd = formsauthentication.hashpasswordforstoringinconfigfile(saltandpwd, "sha1");
      //转为小写字符并截取前16个字符串
      hashenpwd = hashenpwd.tolower().substring(0, 16);
      //返回哈希后的值
      return hashenpwd;
    }
  }
}

3.最后防止上传大文件图片时报错,配置文件添加配置web.config

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
 
<!--
 有关如何配置 asp.net 应用程序的详细消息,请访问
 http://go.microsoft.com/fwlink/?linkid=169433
 -->
 
<configuration>
  <system.web>
   <compilation debug="true" targetframework="4.0" />
   <httpruntime executiontimeout="240" maxrequestlength="8192000"/>
  </system.web>
 
</configuration>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。