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

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

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

具体实现代码如下:

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.后台代码UploadPic.aspx.cs

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

<?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>

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

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索c#上传图片
c#多图片上传
c站、c语言、cf、ch、c罗,以便于您获取更多的相关知识。

时间: 2024-08-01 06:50:12

c#图片上传和显示的实现方法_C#教程的相关文章

ruby on rails爬坑图片上传及显示的实例

一,问题及思路 最近在用 rails + react + mysql 基本框架写一个cms + client的项目,里面涉及到了图片的上传及显示,下面简单说说思路,至于这个项目的配置部署,应该会在寒假结束总结分享一下. rails中图片上传及显示要解决主要问题是: 图片存在哪? 图片格式大小? 客户端怎么显示图片? 因为这是个小项目,估计最多1000张图片,最多占用空间1G,所以采取相对简便的方法: 图片保存在rails的public文件夹里(也就是保存在部署该项目的主机中) ,如果图片比较多的

jquery实现图片上传之前预览的方法_jquery

本文实例讲述了jquery实现图片上传之前预览的方法.分享给大家供大家参考.具体实现方法如下: <!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">

常用图片上传带预览功能方法

常用图片上传带预览功能方法 一下为常见的图片预览实现方式,但是当远程访问该页面 的时候仍然会出现无法预览的情况,但是很多人用,应该也会发现有问题.代码如下.   <%@ page language="c#" autoeventwireup="true" codefile="photoupload.asp教程x.cs" inherits="photoupload" %> <!doctype html publi

图片上传即时显示缩略图的js代码_图象特效

<script language="javascript" type="text/javascript"> var allowExt = ['jpg', 'gif', 'bmp', 'png', 'jpeg']; var preivew = function(file, container){ try{ var pic = new Picture(file, container); }catch(e){ alert(e); } } //缩略图类定义 va

yii实现图片上传及缩略图生成的方法_php实例

本文实例讲述了利用yii框架来实现图片上传功能并在上传成功之后自动生成缩略图的方法,分享给大家供大家参考.具体实现方法如下: Action文件: 复制代码 代码如下: <?php /**  * TestController.php  * Created on: 2014-1-26 12:59:36 by Outsider  */ class TestController extends CController {       /**      * 缩略图片生成      * @ path 图片路

WPF中的ListBox实现按块显示元素的方法_C#教程

本文实例讲述了WPF中的ListBox实现按块显示元素的方法.分享给大家供大家参考,具体如下: 注意:需要设置ListBox的属性 ScrollViewer.HorizontalScrollBarVisibility="Disabled" 关键代码,WPF中有内置的WrapPanel控件,在ListBox.ItemsPanel中使用可以让元素按块显示 <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel/

关于图片上传和显示的问题,急用

问题描述 我在开发c/s结构系统,需要这样的功能:在一个window窗口里放入一个能够上传图片的控件就是让用户点击后在自己的机子上找到所需要的图片,然后通过这个控件保存到数据库中(SqlServer2005),然后再所需要的地方显示出来,请问在.net的window自带的控件怎样实现这样的功能呀,请给出详细代码和解释,谢谢,等待中 解决方案 解决方案二:好像系统没有带这功能的自带控件吧.解决方案三:怎么没人知道啊?解决方案四:http://blog.csdn.net/hank212解决方案五:我

asp.net 将图片上传到mysql数据库的方法_Mysql

这是页面上的按钮单击事件 复制代码 代码如下: protected void Button1_Click(object sender, EventArgs e) { string tid = Utils.getRandom(32); Stream mystream = this.FileUpload1.PostedFile.InputStream; int length = this.FileUpload1.PostedFile.ContentLength; byte[] pic = new b

C#实现在控制台输入密码显示星号的方法_C#教程

在控制台输入的内容C#默认按照字符串进行处理,如果直接让用户一次输入完毕就很难实现 显示星号的功能.但是如果让用户一次只能输入一个字符就,在将用户输入的字符替换为星号就可以实现了! 首先,C#中能让用户按下一个按键的方法就是Console.Readkey(),用户一次只能按下一个按键,其中它的另外一个重载方法是Console.ReadKey(bool b),bool类型的参数用来控制是否在控制台上显示用户按下的按键.那么我们可以传入true参数,使用户按下的按键不显示在控制台上,这样光标始终停留