asp.Net_图片上传的一个类库的源码
一般情況.圖片是不直接存到數(shù)據(jù)庫的.而只是存了圖片的名稱.
存放圖片的文件夾路徑一般是固定的.
所以這時你只需要從數(shù)據(jù)庫拿出圖片名稱.直接在頁面中這么寫就OK了:<img src="yourPath/<%=讀出的圖片名%>">
在上傳的時候.首先當然是要判斷上傳文件是不是圖片了.不建議去判斷文件的后綴名.用這個方法:
if(this.myfile.PostedFile.ContentType.ToString().ToLower().IndexOf("image")<0){
//非圖片文件
}
在對圖片刪除的時候.先去數(shù)據(jù)庫里刪除相關(guān)圖片信息.然后再用:
System.IO.File.Delete(@"C:\ccc\ddd\eee.gif");
這里一定要用絕對路徑.
上傳圖片到服務(wù)器上是網(wǎng)站開發(fā)中很常用的功能,它的實現(xiàn)也很簡單,可以新建一個上傳類UpLoadAndSaveImage,這個類中包含三個函數(shù)UpLoadAndSave,CreateFilePath,SaveToServer。使用時調(diào)用下面的UpLoadAndSave函數(shù)就可以了,該函數(shù)第一個參數(shù)為要上傳的圖片數(shù)據(jù),第二個參數(shù)為上傳的虛擬路徑(相對路徑),第三個參數(shù)為上傳圖片的格式,第四個參數(shù)為上傳的物理路徑。在這個函數(shù)中調(diào)用CreateFilePath函數(shù)產(chǎn)生隨機的圖片名稱,最后再調(diào)用SaveToServer保存圖片到服務(wù)器上。
public string UpLoadAndSave(byte[] data,refstring virPath,string fext,string physicPath)
{
// 返回文件物理地址,修改虛擬地址
if(data==null||virPath==null||fext==null||physicPath=="")
{
throw new Exception(" 非法參數(shù)" );
}
string rtnValue=SaveToServer(data,fext,physicPath,data.Length);
virPath += rtnValue;
physicPath+=rtnValue;
return physicPath;
}
private string CreateFilePath(string fext)
{
string filePath="";
Random rd=new Random();
filePath+=DateTime.Now.Year.ToString("0000");
filePath+=DateTime.Now.Month.ToString("00");
filePath+=DateTime.Now.Date.ToString("00");
filePath+=DateTime.Now.Hour.ToString("00");
filePath+=DateTime.Now.Minute.ToString("00");
filePath+=DateTime.Now.Second.ToString("00");
filePath+=DateTime.Now.Millisecond.ToString("00");
filePath+=rd.Next(99).ToString("00");
filePath+="."+fext;
return filePath;
}
private string SaveToServer(byte[] data,string fext,string physicPath,int fileLen)
{
string filePath=CreateFilePath(fext);
string rtnValue=filePath;
filePath=filePath.Insert(0,@physicPath);
if(File.Exists(filePath))
{
filePath=CreateFilePath(fext);
rtnValue=filePath;
}
FileStream fs=new FileStream(filePath,FileMode.CreateNew);
fs.Write(data,0,fileLen);
fs.Close();
return rtnValue;
}
//在其他頁面調(diào)用該上傳類,見下面的實例:
UpLoadAndSaveImage upload=new UpLoadAndSaveImage();
try
{
string virPath="UploadFiles/";
string physicPath=Server.MapPath(Request.ApplicationPath+"/"+"UploadFiles/");
string fext=this.File1.PostedFile.FileName;
if(fext.Length==0)
{
return;
}
fext=Path.GetExtension(fext).ToLower();
if(fext!=".jpg"&&fext!=".gif"&&fext!=".bmp"&&fext!=".doc"&&fext!=".rar"&&fext!=".zip"&&fext!=".jpeg")
{
Response.Write("<script>alert('Invalid file format,the file format must be jpg or jpeg or gif
or bmp or doc or rar or zip')</script>");
return;
}
byte[] data=newbyte[this.File1.PostedFile.ContentLength];
this.File1.PostedFile.InputStream.Read(data,0,this.File1.PostedFile.ContentLength);
physicPath=upload.UpLoadAndSave(data,ref virPath,fext,physicPath);
url=virPath;
if(Session["PhotoUrl"]==null)
{
ArrayList al=new ArrayList();
al.Add(physicPath);
Session["PhotoUrl"]=al;
}
else
{
ArrayList al2=(ArrayList)Session["PhotoUrl"];
al2.Add(physicPath);
Session["PhotoUrl"]=al2;
}
}
catch(Exception ex)
{
Response.Write("<script>alert('"+ex.Message+"');</script>");
}
// 如果要指定上傳圖片的大小,可以在調(diào)用該上傳類前生成,見下面的實例:
try
{
empPic = new Bitmap(File1.PostedFile.InputStream);
}
catch
{
Script.Alert(" 圖片格式錯誤!" );
return false;
}
Bitmap picSmall = new Bitmap(empPic,227,91); // 生成圖片大小
MemoryStream stream = new MemoryStream();
picSmall.Save(stream,ImageFormat.Jpeg);
byte[] byteArray = stream.ToArray();
PathName1="Photo/";
PathName=Server.MapPath(Request.ApplicationPath+"/Photo/");
UpLoadAndSaveImage upimage=new UpLoadAndSaveImage();
PathName=upimage.UpLoadAndSave(byteArray,ref PathName1,".jpg",PathName);
以下是我曾經(jīng)寫的圖片上傳類,帶水印功能:
//生成縮略圖功能。
using System;
using System.IO;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Drawing;
namespace MyUplod
{
??? /// <summary>
??? /// 非寒上傳類(圖片)。 作者:非寒.功能:上傳文件操作(主要用于圖片上傳);
??? /// </summary>
??? public class Upload
??? {
??????? private int _Error = 0;//返回上傳狀態(tài)。
??????? private int _MaxSize = 5120000;//最大單個上傳文件 (默認)
??????? private string _FileType = "jpg/gif/bmp/png";//所支持的上傳類型用"/"隔開
??????? private string _SavePath = System.Web.HttpContext.Current.Server.MapPath(".") + "\\";//保存文件的實際路徑
??????? private int _SaveType = 0;//上傳文件的類型,0代表自動生成文件名
??????? private HtmlInputFile _FormFile;//上傳控件。
??????? private string _InFileName = "";//非自動生成文件名設(shè)置。
??????? private string _OutFileName = "";//輸出文件名。
??????? private bool _IsCreateImg = true;//是否生成縮略圖。
??????? private bool _Iss = false;//是否有縮略圖生成.
??????? private int _Height = 0;//獲取上傳圖片的高度
??????? private int _Width = 0;//獲取上傳圖片的寬度
??????? private int _sHeight = 120;//設(shè)置生成縮略圖的高度
??????? private int _sWidth = 120;//設(shè)置生成縮略圖的寬度
??????? private bool _IsDraw = false;//設(shè)置是否加水印
??????? private int _DrawStyle = 0;//設(shè)置加水印的方式0:文字水印模式,1:圖片水印模式,2:不加
??????? private int _DrawString_x = 10;//繪制文本的X坐標(左上角)
??????? private int _DrawString_y = 10;//繪制文本的Y坐標(左上角)
??????? private string _AddText = "杭州五維多媒體\nHTTP://WWW.5D.CN";//設(shè)置水印內(nèi)容
??????? private string _Font = "宋體";//設(shè)置水印字體
??????? private int _FontSize = 12;//設(shè)置水印字大小
??????? private int _FileSize = 0;//獲取已經(jīng)上傳文件的大小
??????? private string _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(".") + "/images/5dm_new.jpg";//圖片水印模式下的覆蓋圖片的實際地址
???????
??????? /// <summary>
??????? /// Error返回值,1、沒有上傳的文件。2、類型不允許。3、大小超限。4、未知錯誤。0、上傳成功。
??????? /// </summary>
??????? public int Error
??????? {
??????????? get { return _Error; }
??????? }
??????? /// <summary>
??????? /// 最大單個上傳文件
??????? /// </summary>
??????? public int MaxSize
??????? {
??????????? set { _MaxSize = value; }
??????? }
??????? /// <summary>
??????? /// 所支持的上傳類型用"/"隔開
??????? /// </summary>
??????? public string FileType
??????? {
??????????? set { _FileType = value; }
??????? }
??????? /// <summary>
??????? /// //保存文件的實際路徑
??????? /// </summary>
??????? public string SavePath
??????? {
??????????? set { _SavePath = System.Web.HttpContext.Current.Server.MapPath(value); }
??????????? get {return _SavePath;}
??????? }
??????? /// <summary>
??????? /// 上傳文件的類型,0代表自動生成文件名
??????? /// </summary>
??????? public int SaveType
??????? {
??????????? set { _SaveType = value; }
??????? }
??????? /// <summary>
??????? /// 上傳控件
??????? /// </summary>
??????? public HtmlInputFile FormFile
??????? {
??????????? set { _FormFile = value; }
??????? }
??????? /// <summary>
??????? /// //非自動生成文件名設(shè)置。
??????? /// </summary>
??????? public string InFileName
??????? {
??????????? set { _InFileName = value; }
??????? }
??????? /// <summary>
??????? /// 輸出文件名
??????? /// </summary>
??????? public string OutFileName
??????? {
??????????? get { return _OutFileName; }
??????????? set { _OutFileName = value; }
??????? }
??????? /// <summary>
??????? /// 是否有縮略圖生成.
??????? /// </summary>
??????? public bool Iss
??????? {
??????????? get { return _Iss; }
??????? }
??????? /// <summary>
??????? /// //獲取上傳圖片的寬度
??????? /// </summary>
??????? public int Width
??????? {
??????????? get { return _Width; }
??????? }
??????? /// <summary>
??????? /// //獲取上傳圖片的高度
??????? /// </summary>
??????? public int Height
??????? {
??????????? get { return _Height; }
??????? }
??????? /// <summary>
??????? /// 設(shè)置縮略圖的寬度
??????? /// </summary>
??????? public int sWidth
??????? {
??????????? get { return _sWidth; }
??????????? set { _sWidth = value; }
??????? }
??????? /// <summary>
??????? /// 設(shè)置縮略圖的高度
??????? /// </summary>
??????? public int sHeight
??????? {
??????????? get { return _sHeight; }
??????????? set { _sHeight = value; }
??????? }
??????? /// <summary>
??????? /// 是否生成縮略圖
??????? /// </summary>
??????? public bool IsCreateImg
??????? {
??????????? get { return _IsCreateImg; }
??????????? set { _IsCreateImg = value; }
??????? }
??????? /// <summary>
??????? /// 是否加水印
??????? /// </summary>
??????? public bool IsDraw
??????? {
??????????? get { return _IsDraw; }
??????????? set { _IsDraw = value; }
??????? }
??????? /// <summary>
??????? /// 設(shè)置加水印的方式0:文字水印模式,1:圖片水印模式,2:不加
??????? /// </summary>
??????? public int DrawStyle
??????? {
??????????? get { return _DrawStyle; }
??????????? set { _DrawStyle = value; }
??????? }
??????? /// <summary>
??????? /// 繪制文本的X坐標(左上角)
??????? /// </summary>
??????? public int DrawString_x
??????? {
??????????? get { return _DrawString_x; }
??????????? set { _DrawString_x = value; }
??????? }
??????? /// <summary>
??????? /// 繪制文本的Y坐標(左上角)
??????? /// </summary>
??????? public int DrawString_y
??????? {
??????????? get { return _DrawString_y; }
??????????? set { _DrawString_y = value; }
??????? }
??????? /// <summary>
??????? /// 設(shè)置文字水印內(nèi)容
??????? /// </summary>
??????? public string AddText
??????? {
??????????? get { return _AddText; }
??????????? set { _AddText = value; }
??????? }
??????? /// <summary>
??????? /// 設(shè)置文字水印字體
??????? /// </summary>
??????? public string Font
??????? {
??????????? get { return _Font; }
??????????? set { _Font = value; }
??????? }
??????? /// <summary>
??????? /// 設(shè)置文字水印字的大小
??????? /// </summary>
??????? public int FontSize
??????? {
??????????? get { return _FontSize; }
??????????? set { _FontSize = value; }
??????? }
??????? public int FileSize
??????? {
??????????? get { return _FileSize; }
??????????? set { _FileSize = value; }
??????? }
??????? /// <summary>
??????? /// 圖片水印模式下的覆蓋圖片的實際地址
??????? /// </summary>
??????? public string CopyIamgePath
??????? {
??????????? set { _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(value); }
??????? }
???????
??????? //獲取文件的后綴名
??????? private string GetExt(string path)
??????? {
??????????? return Path.GetExtension(path);
??????? }
??????? //獲取輸出文件的文件名。
??????? private string FileName(string Ext)
??????? {
??????????? if (_SaveType == 0 || _InFileName.Trim() == "")
??????????????? return DateTime.Now.ToString("yyyyMMddHHmmssfff") + Ext;
??????????? else
??????????????? return _InFileName;
??????? }
??????? //檢查上傳的文件的類型,是否允許上傳。
??????? private bool IsUpload(string Ext)
??????? {
??????????? Ext = Ext.Replace(".", "");
??????????? bool b = false;
??????????? string[] arrFileType = _FileType.Split(';');
??????????? foreach (string str in arrFileType)
??????????? {
??????????????? if (str.ToLower() == Ext.ToLower())
??????????????? {
??????????????????? b = true;
??????????????????? break;
??????????????? }
??????????? }
??????????? return b;
??????? }
??????? //上傳主要部分。
??????? public void Open()
??????? {
??????????? HttpPostedFile hpFile = _FormFile.PostedFile;
??????????? if (hpFile == null || hpFile.FileName.Trim() == "")
??????????? {
??????????????? _Error = 1;
??????????????? return;
??????????? }
??????????? string Ext = GetExt(hpFile.FileName);
??????????? if (!IsUpload(Ext))
??????????? {
??????????????? _Error = 2;
??????????????? return;
??????????? }
??????????? int iLen = hpFile.ContentLength;
??????????? if (iLen > _MaxSize)
??????????? {
??????????????? _Error = 3;
??????????????? return;
??????????? }
??????????? try
??????????? {
??????????????
??????????????????? if (!Directory.Exists(_SavePath))
??????????????????????? Directory.CreateDirectory(_SavePath);
??????????????????? byte[] bData = new byte[iLen];
??????????????????? hpFile.InputStream.Read(bData, 0, iLen);
??????????????????? string FName;
??????????????????? FName = FileName(Ext);
??????????????????? string TempFile = "";
??????????????????? if (_IsDraw)
??????????????????? {
??????????????????????? TempFile=FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString();
??????????????????? }
??????????????????? else
??????????????????? {
??????????????????????? TempFile = FName;
??????????????????? }
??????????????????? FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
??????????????????? newFile.Write(bData, 0, bData.Length);
??????????????????? newFile.Flush();
??????????????????? int _FileSizeTemp = hpFile.ContentLength;
???????????????????
??????????????????? if (_IsDraw)
??????????????????? {
??????????????????????? if (_DrawStyle == 0)
??????????????????????? {
??????????????????????????? System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
??????????????????????????? Graphics g = Graphics.FromImage(Img1);
??????????????????????????? g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height);
??????????????????????????? Font f = new Font(_Font, _FontSize);
??????????????????????????? Brush b = new SolidBrush(Color.Red);
??????????????????????????? string addtext = _AddText;
??????????????????????????? g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
??????????????????????????? g.Dispose();
??????????????????????????? Img1.Save(_SavePath + FName);
??????????????????????????? Img1.Dispose();
??????????????????????? }
??????????????????????? else
??????????????????????? {
??????????????????????????? System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
??????????????????????????? System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
??????????????????????????? Graphics g = Graphics.FromImage(image);
??????????????????????????? g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 5, image.Height - copyImage.Height - 5, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
??????????????????????????? g.Dispose();
??????????????????????????? image.Save(_SavePath + FName);
??????????????????????????? image.Dispose();
??????????????????????? }
??????????????????? }
??????????????? try
??????????????? {
??????????????????? //獲取圖片的高度和寬度
??????????????????? System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
??????????????????? _Width = Img.Width;
??????????????????? _Height = Img.Height;
??????????????????? //生成縮略圖部分
??????????????????? if (_IsCreateImg)
??????????????????? {
??????????????????????? //如果上傳文件小于15k,則不生成縮略圖。
??????????????????????? if (iLen > 15360)
??????????????????????? {
??????????????????????????? System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
??????????????????????????? newImg.Save(_SavePath + FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString());
??????????????????????????? newImg.Dispose();
??????????????????????????? _Iss = true;
??????????????????????? }
??????????????????? }
??????????????????? if (_IsDraw)
??????????????????? {
??????????????????????? if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()))
??????????????????????? {
??????????????????????????? newFile.Dispose();
??????????????????????????? File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString());
??????????????????????? }
??????????????????? }
??????????????? }
??????????????? catch { }
??????????????? newFile.Close();
??????????????? newFile.Dispose();
??????????????? _OutFileName = FName;
??????????????? _FileSize = _FileSizeTemp;
??????????????? _Error = 0;
??????????????? return;
??????????? }
??????????? catch
??????????? {
??????????????? _Error = 4;
??????????????? return;
??????????? }
??????? }
??? }
}
?
總結(jié)
以上是生活随笔為你收集整理的asp.Net_图片上传的一个类库的源码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 霸气群名字大全853个
- 下一篇: Calendar详解