asp.net上传图片的示例代码
本文导语: 本节内容: asp.net上传图片 1,aspx页面内容 代码示例: 2,图片上传页面 代码示例: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; usin...
本节内容:
asp.net上传图片
1,aspx页面内容
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.
// 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 = "文件类型不对上传失败";
}
}
}
使用的时候只要引用上路径即可。
要使用的页面头部加上这段代码
在要上传的地方加上
图片路径=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
{
///
/// 上传文件方法
///
/// FileUpload控件的ID
/// 要保存的路径
/// 要上传的文件的类型([图片]image,[文件]file,[多媒体]media,flash)
/// 上传文件重命名时的前缀
/// 上传文件限制的大小,单位是M
/// 正确的时候返回string类型的文件路径,返回0为有错
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;
}
///
///是否允许该扩展名上传
///
///要上传的文件扩展名,如:(.jpg,.gif)
///文件类型(image,image1,media,file,flash)
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;
}
///
/// 获取上传文件存放目录。
///
/// 存放文件的物理路径。
/// 返回存放文件的目录。
private static string GetSaveDirectory(string DirectoryPath)
{
if (!Directory.Exists(DirectoryPath)) // 判断当前目录是否存在。
{
Directory.CreateDirectory(DirectoryPath); // 建立上传文件存放目录。
}
return DirectoryPath;
}
///
/// 获取文件扩展名
///
///
///
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;
}
}
///
/// 获取不带扩展名的文件名
///
///
///
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;
}
}
///
/// 删除指定文件
///
/// 文件绝对路径
private static void DeleteFile(string strAbsolutePath)
{ // www.
//判断要删除的文件是否存在
if (File.Exists(strAbsolutePath))
{
//删除文件
File.Delete(strAbsolutePath);
}
}
///
/// 删除指定文件
///
/// 文件绝对路径
/// 文件名
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);
}
}
}
}
}