圖片上傳

一:    上傳的文件夾(以日期爲文件名) 

           string   strSaveDir   =   "upfiles/";    
  string   strNewName="";  
  if(inputFile.PostedFile.ContentLength   >   0)    
  {    
  //設定上傳文件的保存路徑    
   
  string   strName   =   inputFile.PostedFile.FileName;    
  //取得文件名(抱括路徑)裏最後一個"."的索引    
  int   intExt   =   strName.LastIndexOf(".");    
  //取得文件擴展名    
  string   strExt   =   strName.Substring(intExt);    
  //這裏我自動根據日期和文件大小不同爲文件命名,確保文件名不重複    
   
  if   (strExt.ToLower().Equals("gif")||   strExt.ToLower().Equals("jpg"))  
  {  
  Response.Write("<script   language=javascript>alert('文件只能爲jpg或者gif!');</script>");  
  return;  
  }  
   
  DateTime   datNow   =   DateTime.Now;    
  int   temp;  
  temp=datNow.Year;  
   
  StringBuilder   builder   =   new   StringBuilder();  
  builder.Append(temp);  
   
  temp=datNow.Month;  
  if   (temp<10)  
  builder.Append('0');  
  builder.Append(temp);  
  temp=datNow.Day;  
  if   (temp<10)  
  builder.Append('0');  
  builder.Append(temp);  
   
  temp=datNow.Hour;  
  if   (temp<10)  
  builder.Append('0');  
  builder.Append(temp);  
   
  temp=datNow.Minute;  
  if   (temp<10)  
  builder.Append('0');  
  builder.Append(temp);  
   
  temp=datNow.Second;  
  if   (temp<10)  
  builder.Append('0');  
  builder.Append(temp);  
  temp=datNow.Millisecond;  
  builder.Append(temp);  
   
   
  strNewName   =   builder.Append(strExt).ToString();    
  //取得文件名(包括路徑)裏最後一個"/"的索引    
  int   intPath   =   strName.LastIndexOf("//");    
  //取得文件名(不包括路徑)    
   
  //保存文件到你所要的目錄,這裏是IIS根目錄下的upload目錄.你可以改變.    
  //注意:   我這裏用Server.MapPath()取當前文件的絕對目錄.在asp.net裏"/"必須用"//"代替    
  inputFile.PostedFile.SaveAs(Server.MapPath(strSaveDir   +   strNewName));    
  }  
  string   PhotoUrl   =strSaveDir   +strNewName;  
   
  PhotoUrl是獲取上傳路徑文件的路徑和文件名.可以存到數據庫裏面去

using   System.Text;記得加這個

 

 

二:圖片上傳並自動生成縮略圖的asp.net(C#)源代碼


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;

namespace eMeng.Exam
{
/// <summary>
/// Thumbnail 的摘要說明。
/// </summary>
public class Thumbnail : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置用戶代碼以初始化頁面
Label1.Text = "<h3>在ASP.NET裏輕鬆實炙趼醞?lt;/h3>";
Button1.Text = "上載並顯示縮略圖";

}

#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
HttpFileCollection MyFileColl = HttpContext.Current.Request.Files;
HttpPostedFile MyPostedFile = MyFileColl[0];

if (MyPostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0)
{
Response.Write("無效的圖形格式。");
return;
}
GetThumbNail(MyPostedFile.FileName, 100, 100,
MyPostedFile.ContentType.ToString(), false, MyPostedFile.InputStream);
}
private System.Drawing.Imaging.ImageFormat GetImageType(object strContentType)
{
if ((strContentType.ToString().ToLower()) == "image/pjpeg")
{
return System.Drawing.Imaging.ImageFormat.Jpeg;
}
else if ((strContentType.ToString().ToLower()) == "image/gif")
{
return System.Drawing.Imaging.ImageFormat.Gif;
}
else if ((strContentType.ToString().ToLower()) == "image/bmp")
{
return System.Drawing.Imaging.ImageFormat.Bmp;
}
else if ((strContentType.ToString().ToLower()) == "image/tiff")
{
return System.Drawing.Imaging.ImageFormat.Tiff;
}
else if ((strContentType.ToString().ToLower()) == "image/x-icon")
{
return System.Drawing.Imaging.ImageFormat.Icon;
}
else if ((strContentType.ToString().ToLower()) == "image/x-png")
{
return System.Drawing.Imaging.ImageFormat.Png;
}
else if ((strContentType.ToString().ToLower()) == "image/x-emf")
{
return System.Drawing.Imaging.ImageFormat.Emf;
}
else if ((strContentType.ToString().ToLower()) == "image/x-exif")
{
return System.Drawing.Imaging.ImageFormat.Exif;
}
else if ((strContentType.ToString().ToLower()) == "image/x-wmf")
{
return System.Drawing.Imaging.ImageFormat.Wmf;
}
else
{
return System.Drawing.Imaging.ImageFormat.MemoryBmp;
}
}

private void GetThumbNail(string strFileName, int iWidth, int iheight,
string strContentType, bool blnGetFromFile, System.IO.Stream ImgStream)
{
System.Drawing.Image oImg;

if (blnGetFromFile)
{
oImg = System.Drawing.Image.FromFile(strFileName);
}
else
{
oImg = System.Drawing.Image.FromStream(ImgStream);
}
oImg = oImg.GetThumbnailImage(iWidth, iheight, null, IntPtr.Zero);
string strGuid = System.Guid.NewGuid().ToString().ToUpper();
string strFileExt = strFileName.Substring(strFileName.LastIndexOf("."));
Response.ContentType = strContentType;
MemoryStream MemStream = new MemoryStream();
oImg.Save(MemStream, GetImageType(strContentType));
MemStream.WriteTo(Response.OutputStream);
}

}
}
功能:
1。把圖片文件(JPG GIF PNG)上傳,
2。保存到指定的路徑(在web.config中設置路徑,以文件的原有格式保存),
3。並自動生成指定寬度的(在web.config中設置寬度)
4。和指定格式的(在web.config中指定縮略圖的格式)
5。和原圖比例相同的縮略圖(根據寬度和原圖的寬和高計算所略圖的高度)
6。可以判斷是否已經存在文件
7。如果不覆蓋,則給出錯誤
8。如果選中"覆蓋原圖"checkbox,則覆蓋原圖。
9。可以根據要求,在webform上設置1個以上的file input和相應的checkbox
10。並在文件上傳完畢後,顯示原圖的文件名,尺寸,字節,和
11。縮略圖的文件名尺寸。
12。縮略圖的文件名格式:原圖+"_thumb."+指定格式,如:test.jpg_thumb.gif,以便於管理。

--------------------
public void UploadFile(object sender, System.EventArgs e)
{

string imgNameOnly, imgNameNoExt, imgExt;
string imgThumbnail;
int erroNumber = 0;
System.Drawing.Image oriImg, newImg;
string strFePicSavePath = ConfigurationSettings.AppSettings["FePicSavePath"].ToString();
string strFePicThumbFormat = ConfigurationSettings.AppSettings["FePicThumbFormat"].ToString().ToLower();
int intFeThumbWidth = Int32.Parse(ConfigurationSettings.AppSettings["FePicThumbWidth"]);
string fileExt;

StringBuilder picInfo = new StringBuilder();

if(Page.IsValid)
{


for(int i = 0;i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
fileExt = (System.IO.Path.GetExtension(PostedFile.FileName)).ToString().ToLower();

imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName);
if(fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".png")
{

if(System.IO.File.Exists(strFePicSavePath + imgNameOnly) && (checkboxlistRewrite.Items[i].Selected == false))
{
erroNumber = erroNumber + 1;
picInfo.Append("<b>錯誤:</b>文件("+ (i+1) +") " + imgNameOnly + " 已經存在,請修改文件名<br/>" );
}
}
else
{
erroNumber = erroNumber + 1;
picInfo.Append("<b>錯誤:</b>文件("+ (i+1) +") " + imgNameOnly + " 擴展名 " + fileExt + " 不被許可<br/>" );
}

}

if(erroNumber > 0)
{
picInfo.Append("<font color=red>全部操作均未完成,請修改錯誤,再進行操作</font><br/>");
}
else
{
for(int i = 0;i < Request.Files.Count; i++)
{

HttpPostedFile PostedFile = Request.Files[i];
imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName);
imgNameNoExt = System.IO.Path.GetFileNameWithoutExtension(PostedFile.FileName);
imgExt = System.IO.Path.GetExtension(PostedFile.FileName).ToString().ToLower();


oriImg = System.Drawing.Image.FromStream(PostedFile.InputStream);
newImg = oriImg.GetThumbnailImage(intFeThumbWidth, intFeThumbWidth * oriImg.Height/oriImg.Width,null,new System.IntPtr(0));
switch(imgExt)
{
//case ".jpeg":
case ".jpg":
oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".gif":
oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".png":
oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Png);
break;
}

//oriImg.Save(ConfigurationSettings.AppSettings["FePicSavePath"] + imgNameNoExt + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

switch(strFePicThumbFormat)
{
//jpeg format can get the smallest file size, and the png is the largest size
//case "jpeg":
case "jpg":
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
imgThumbnail = imgNameOnly + "_thumb.jpg";
break;
case "gif":
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.gif",System.Drawing.Imaging.ImageFormat.Gif);
imgThumbnail = imgNameOnly + "_thumb.gif";
break;
case "png":
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.png",System.Drawing.Imaging.ImageFormat.Png);
imgThumbnail = imgNameOnly + "_thumb.png";
break;
default:
newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
imgThumbnail = imgNameOnly + "_thumb.jpg";
break;

}//switch

picInfo.Append("<b>文件 名:</b>" + imgNameOnly + " ( " + oriImg.Width + " x " + oriImg.Height + " ) " + PostedFile.ContentLength/1024 + "KB<br/>");
picInfo.Append("<b>縮略圖名:</b>" + imgThumbnail + " ( " + newImg.Width + " x " + newImg.Height + " )<br/><br/>");

oriImg.Dispose();
newImg.Dispose();

}//for
picInfo.Append("<font color=red>所有操作成功</font><br/>");

}// if erronumber = 0

 

}
else
{
picInfo.Append("<font color=red>有錯誤,請檢查。操作未成功</font><br/>");

}

lblPicInfo.Text = picInfo.ToString();

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章