ASP.NET图片上传实例(附源码)

所属分类: 网络编程 / ASP.NET 阅读数: 460
收藏 0 赞 0 分享

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

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

下面是代码:
1.界面代码

<%@ 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.后台代码

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.最后防止上传大文件图片时报错,配置文件添加配置

<?xml version="1.0" encoding="utf-8"?>

<!--
 如何配置 ASP.NET 应用程序的详细消息
 -->

<configuration>
 <system.web>
 <compilation debug="true" targetFramework="4.0" />
 <httpRuntime executionTimeout="240" maxRequestLength="8192000"/>
 </system.web>

</configuration>

ASP.NET图片自动上传和局部刷新显示的源码下载。

希望大家喜欢这篇文章。

更多精彩内容其他人还在看

asp.net 虚方法、抽象方法、接口疑问

asp.net 虚方法、抽象方法、接口疑问等说明。
收藏 0 赞 0 分享

c#  操作符?? null coalescing operator

?? "null coalescing" operator 是c#新提供的一个操作符,这个操作符提供的功能是判断左侧的操作数是否是null,如果是则返回结果是右侧的操作数;非null则返回左侧的操作数。
收藏 0 赞 0 分享

.net 反序题目的详细解答第1/2页

在各种答案,以及平时面试过程中,这道题总归会有一些非常典型的错误发生。其中给老赵的感觉也非常有意思,不知其中的“思路”是否如老赵猜测那样。
收藏 0 赞 0 分享

implicitly convert type 'int' to 'short'的原因与解决方法

implicitly convert type 'int' to 'short'的原因与解决方法
收藏 0 赞 0 分享

比较完整的 asp.net 学习流程

好多朋友想学习后台编程语言,但请注意的事,学习后台是个循序渐进的过程,不可能一下就到位,其实不只是asp.net其它的编程语言都需要下面的一些知识。
收藏 0 赞 0 分享

官网 Ext direct包中.NET版的问题

下载了官网的 Ext direct 包进行研究,发现服务器端返回结果存在一点小问题。
收藏 0 赞 0 分享

C# XML操作 代码大全(读XML,写XML,更新,删除节点,与dataset结合等)第1/2页

C#操作XML(读XML,写XML,更新,删除节点,与dataset结合等),以下就是操作XML的所有方法,相信可以满足很大一部份的使用了。
收藏 0 赞 0 分享

c# 连接字符串数据库服务器端口号 .net状态服务器端口号

正常的数据库连接字符串配置,这是在MSSQL服务器端口是1433(默认)的情况下。
收藏 0 赞 0 分享

ASP.NET 路径问题的解决方法

相对路径和绝对路径在ASP.NET中可以用~/来解决.
收藏 0 赞 0 分享

asp.net TemplateField模板中的Bind方法和Eval方法

在TemplateField模板中为了能够有限制的或者取出数据库中某列的值时,可以用Bind和Eval方法来实现。以下是Bind方法的格式,Eval的格式也是和Bind一样的。 Bind("列的名称","显示的格式文")
收藏 0 赞 0 分享
查看更多