asp.net上传图片的示例代码

发布时间:2019-12-04编辑:脚本学堂
分享一例asp.net实现图片上传的代码,比较简单,可以作为asp.net上传文件的初学案例,有需要的朋友参考下吧。

本节内容:
asp.net上传图片

1,aspx页面内容
 

复制代码 代码示例:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="upfile.ascx.cs" Inherits="mycontrols_upfile" %>
 <table>
<tr>
<td><asp:TextBox ID="fileimages" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Font-Size="12px" ForeColor="Red" Text="类型png,jpg,gif,bmp"
    Width="148px"></asp:Label>
<asp:Label ID="Label1" runat="server" Width="137px" Font-Size="12px" ForeColor="Red"></asp:Label></td>
</tr>
<tr>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
 &nbsp;<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="提交" /><br /></td>
 </tr>
</table>

2,图片上传页面
 

复制代码 代码示例:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class mycontrols_upfile : System.Web.UI.UserControl
{
    private string _filepath;
    public string Filepath
    {
get { return _filepath; }
set { _filepath = value; }
    }
    public string getpath()
    {
this.Filepath = this.fileimages.Text;
return Filepath;
    }
    public string gopath(string str)
    {
this.fileimages.Text= str;
return str;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
if (!IsPostBack)
{ // www.jb200.com
// MenuDAL.Current.BoundTree(TreeView1.Nodes);
DataAccess.IsAdmin();
}
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      string name = this.FileUpload1.FileName;//文件名字
string size = this.FileUpload1.PostedFile.ContentLength.ToString();//文件大小
string type = this.FileUpload1.PostedFile.ContentType;//文件类型type == "image/pjpeg" || type == "image/gif" || type == "x-png"
  string type2 = name.Substring(name.LastIndexOf(".") + 1);//文件类型
  string path = Server.MapPath("~/fileload/") + "//" + DateTime.Now.ToString("yyyyMMddhhmmssffff") + "." + type2; ;//实际路径
  string datapath = "fileload/" + DateTime.Now.ToString("yyyyMMddhhmmssffff") +"."+ type2;
if (Convert.ToInt32(size) > 2048)

this.Label1.Text = "上传失败文件大于2m";
}

if (type == "image/gif" || type == "image/bmp" || type == "image/pjpeg" || type == "image/x-png")
{
    this.FileUpload1.SaveAs(path);
    this.Label1.Text = "上传成功";
    this.fileimages.Text = datapath;
}
else
{
    this.Label1.Text = "文件类型不对上传失败";
}      
    }
}
使用的时候只要引用上路径即可。

要使用的页面头部加上这段代码
<%@ Register src="../upfile.ascx" tagname="upfile" tagprefix="uc1" %>

在要上传的地方加上
<uc1:upfile ID="upfile1" runat="server" />
图片路径=upfile1.getpath();

3,封装的类文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;

namespace Bettem.Utility.IO
{
    public class FileUploadInfo
    {
/// <summary>
/// 上传文件方法
/// </summary>
/// <param name="fileUpload">FileUpload控件的ID</param>
/// <param name="pathDir">要保存的路径</param>
/// <param name="fileType">要上传的文件的类型([图片]image,[文件]file,[多媒体]media,flash)</param>
/// <param name="fileFristName">上传文件重命名时的前缀</param>
/// <param name="fileSize">上传文件限制的大小,单位是M</param>
/// <returns>正确的时候返回string类型的文件路径,返回0为有错</returns>
public  string UpFile(System.Web.UI.WebControls.FileUpload fileUpload,string pathDir,string fileType,string fileFristName,int fileSize)
{

string name = fileUpload.FileName;  //获取文件名字
string getFileExtension = GetExtension(name);   //获取文件扩展名
string getFileNoExtension = GetFileName(name);  //获取文件不带扩展名的名称
if (!IsAllowedExtension(getFileExtension,fileType)) //判断文件的是否为允许上传的文件
{
    return "0";
}
if (fileUpload.PostedFile.ContentLength  > fileSize*1024*1024)
{
    return "1";
}
Random rd = new Random();
string datapath;
try
{
    string path = HttpContext.Current.Server.MapPath("~/" + pathDir + "/") + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + rd.Next().ToString() + getFileNoExtension + getFileExtension;
    string filePahtDir = HttpContext.Current.Server.MapPath("~/" + pathDir + "/");
    GetSaveDirectory(filePahtDir);
    fileUpload.SaveAs(path);
    datapath = "/" + pathDir + "/" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + rd.Next().ToString() + getFileNoExtension + getFileExtension;
}
catch (Exception ex)
{
    throw new Exception(ex.Message);
}
return datapath;
}

///<summary>
///是否允许该扩展名上传
///</summary>
///<param name="fileName">要上传的文件扩展名,如:(.jpg,.gif)</param>
///<param name="flag">文件类型(image,image1,media,file,flash)</param>
private static bool IsAllowedExtension(string fileName, string flag)
{
//string strOldFilePath = "";
string strExtension = "";
string[] arrExtension = { ".zip", ".rar" };

//允许上传的扩展名,可以改成从配置文件中读出
switch (flag)
{
    case "image":
arrExtension = new string[] { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
break;
    case "media":
arrExtension = new string[] { ".avi", ".mpg", ".mpeg", ".mp3", ".wmv", ".wav", ".wma" };
break;
    case "file":
arrExtension = new string[] { ".docx", ".txt", ".doc", ".ppt", ".pptx", ".pdf", ".zip", ".rar", ".swf", ".gif", ".jpg", ".jpeg", ".bmp", ".png", ".xls", ".xlsx", ".rtf", ".avi", ".mpg", ".mpeg", ".mp3", ".wmv", ".wav", ".wma" };
break;
    case "flash":
arrExtension = new string[] { ".swf" };
break;
    default:
break;
}

if (fileName != string.Empty)
{
    //取得上传文件的扩展名
    strExtension = fileName.Substring(fileName.LastIndexOf("."));
    //判断该扩展名是否合法
    for (int i = 0; i < arrExtension.Length; i++)
    {
if (strExtension.ToLower().Equals(arrExtension[i]))
{
return true;
}
    }
}
return false;
}

/// <summary>
/// 获取上传文件存放目录。
/// </summary>
/// <param name="DirectoryPath">存放文件的物理路径。</param>
/// <returns>返回存放文件的目录。</returns>
private static string GetSaveDirectory(string DirectoryPath)
{
if (!Directory.Exists(DirectoryPath))  // 判断当前目录是否存在。
{
    Directory.CreateDirectory(DirectoryPath);  // 建立上传文件存放目录。
}
return DirectoryPath;
}

/// <summary>
/// 获取文件扩展名
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private static string GetExtension(string fileName)
{
try
{
    int startPos = fileName.LastIndexOf(".");
    string ext = fileName.Substring(startPos, fileName.Length - startPos);
    return ext;
}
catch
{
    return string.Empty;
}
}
/// <summary>
/// 获取不带扩展名的文件名
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private static string GetFileName(string fileName)
{
try
{
    fileName = fileName.Replace(@"/", @"");
    int startPos = fileName.LastIndexOf(@"");
    int endPos = fileName.LastIndexOf(@".");
    string ext = fileName.Substring(startPos + 1, fileName.Length - (startPos + 1) - (fileName.Length - endPos));
    return ext;
}
catch
{
    return string.Empty;
}
}
/// <summary>
/// 删除指定文件
/// </summary>
/// <param name="strAbsolutePath">文件绝对路径</param>
private static void DeleteFile(string strAbsolutePath)
{ // www.jb200.com
//判断要删除的文件是否存在
if (File.Exists(strAbsolutePath))
{
    //删除文件
    File.Delete(strAbsolutePath);
}
}
/// <summary>
/// 删除指定文件
/// </summary>
/// <param name="strAbsolutePath">文件绝对路径</param>
/// <param name="strFileName">文件名</param>
private static void DeleteFile(string strAbsolutePath, string strFileName)
{
//判断路径最后有没有符号,没有则自动加上
if (strAbsolutePath.LastIndexOf("") == strAbsolutePath.Length)
{
    //判断要删除的文件是否存在
    if (File.Exists(strAbsolutePath + strFileName))
    {
//删除文件
File.Delete(strAbsolutePath + strFileName);
    }
}
else
{
    if (File.Exists(strAbsolutePath + "" + strFileName))
    {
File.Delete(strAbsolutePath + "" + strFileName);
    }
}
}
    }
}