.Net中FileUpload控制項檔案上傳與驗證實用例子

來源:互聯網
上載者:User

最簡單的fileupload控制項上傳圖片例子

 代碼如下 複製代碼

using System.IO;
protected void Button1_Click(object sender, EventArgs e)
{
Boolean fileOk = false;
//指定檔案路徑,pic是項目下的一個檔案夾;~表示當前網頁所在的檔案夾
String path = Server.MapPath("~/");//物理檔案路徑
//檔案上傳控制項中如果已經包含檔案
if (FileUpload1.HasFile)
{
//得到檔案的尾碼
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
//允許檔案的尾碼
String[] allowedExtensions ={ ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
//看包含的檔案是否是被允許的檔案的尾碼
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOk = true;
}
}
}
if (fileOk)
{
try
{ //檔案另存在伺服器的指定目錄下
FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
Response.Write("<script>alert('檔案上傳成功!');</script>");
}
catch
{
Response.Write("<script>alert('檔案上傳失敗!');</script>");
}
}
else
{
Response.Write("<script>alert('只能上傳gif,png,jpeg,jpg,bmp圖象檔案!');</script>");
}
}

上面的沒做檔案大小判斷只做了圖片類型了,如果要判斷大小我們需要如下設定

在web.config中配置:

 代碼如下 複製代碼

<appSettings>
 <add key="FileType" value=".doc,.xls,.txt,.rar"/>
 <add key="PicTureTye" value=".jpg|.gif|.png|.bmp|.psd|.svg|"/>
 <add key="FileSizeLimit" value="10240"/>
</appSettings>

在.cs檔案中方法實現:
 
檔案大小判斷:

 代碼如下 複製代碼

public bool IsAllowableFileSize()
{
//從web.config讀取判斷檔案大小的限制
double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]);
//判斷檔案是否超出了限制
if (iFileSizeLimit > FileUpload1.PostedFile.ContentLength)
{
Response.Write("檔案剛好");
return true;
}
else
{
Response.Write("檔案太大");
return false;
}
}

好了,看了上面我們看一個完整的例子

 代碼如下 複製代碼

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace CSFramework.BLL
{
/// <summary>
/// 支援上傳的檔案類型
/// </summary>
public enum UploadFileType
{
ArticleAttachment = 1,
Image = 2,
Video = 3,
All = 4
}
  
/// <summary>
/// 上傳檔案管理類
/// </summary>
public class CFileUpload
{
private FileUpload _fileUpload;
private string _savePath;
private string _LastUploadedFile = string.Empty;
private bool _AutoGenFileName = false;
private bool _AutoGenWatermark = false;
public string LastUploadedFile { get { return _LastUploadedFile; } }
private string _Error = "";

private string PICTURE_FILE = "[.gif.png.jpeg.jpg]";
private string ZIP_FILE = "[.zip.rar]";
private string MUILT_MEDIA_FILE = "[.mpeg.mpg.fla.wma]";

private int IMG_MAX_WIDTH = 700;//指定寬度
private int IMG_MAX_HEIGHT = 0;//未指定高度
private int MAX_SIZE_UPLOAD = 1024;//最大支援上傳小於1MB的檔案。

/// <summary>
/// 構造器
/// </summary>
/// <param name="fileUpload">Asp.net FileUpload對象</param>
/// <param name="savePath">儲存目錄,不包含檔案名稱</param>
/// <param name="autoGenFileName">自動組建檔案名</param>
public CFileUpload(FileUpload fileUpload, string savePath, bool autoGenFileName, bool autoGenWatermark)
{
   _savePath = savePath;
   _fileUpload = fileUpload;
   _AutoGenFileName = autoGenFileName;
   _AutoGenWatermark = autoGenWatermark;
}

/// <summary>
/// 構造器
/// </summary>
/// <param name="fileUpload">Asp.net FileUpload對象</param>
/// <param name="savePath">儲存目錄,不包含檔案名稱</param>
public CFileUpload(FileUpload fileUpload, string savePath)
{
   _savePath = savePath;
   _fileUpload = fileUpload;
}

/// <summary>
/// 上傳RAR檔案
/// </summary>
public bool UploadRARFile()
{
   return DoUpload(ZIP_FILE);
}

/// <summary>
/// 上傳視頻檔案
/// </summary>
public bool UploadVideo()
{
   return DoUpload(MUILT_MEDIA_FILE);
}

/// <summary>
/// 上傳圖片檔案
/// </summary>
public bool UploadImage()
{
   return DoUpload(PICTURE_FILE);
}

public bool UploadImage(int maxWidth, int maxHeight)
{
   this.IMG_MAX_WIDTH = maxWidth;
   this.IMG_MAX_HEIGHT = maxHeight;
   return DoUpload(PICTURE_FILE);
}

/// <summary>
/// 上傳任何支援的檔案
/// </summary>
public bool UploadAnySupported()
{
   return DoUpload(PICTURE_FILE ZIP_FILE MUILT_MEDIA_FILE);
}

/// <summary>
/// 產生新的檔案名稱
/// </summary>
private string GetNewFileName(string folder, string fileName)
{
if (_AutoGenFileName) //自動產生32位GUID檔案名稱
{
string ext = System.IO.Path.GetExtension(fileName);
string newfile = Guid.NewGuid().ToString().Replace("-", "") ext;
return folder newfile;
   }
   else
   {
if (System.IO.File.Exists(folder fileName))
{
   string ext = System.IO.Path.GetExtension(fileName);
   string filebody = fileName.Replace(ext, "");
  
   int x = 1;
   while (true) //如果檔案存在,產生尾部帶(x)的檔案
   {
string newfile = folder filebody "(" x.ToString() ")" ext;
if (!System.IO.File.Exists(newfile))
return folder filebody "(" x.ToString() ")" ext;
else
x ;
   }
}
else
return folder fileName;
   }
}

/// <summary>
/// 最大支援小於1MB的檔案。
/// </summary>
private bool AllowMaxSize(int fileLength)
{
   double kb = fileLength / 1024;
   return (int)kb < MAX_SIZE_UPLOAD;
}

private bool DoUpload(string allowedExtensions)
{
try
{
bool fileOK = false;

if (!_fileUpload.HasFile) throw new Exception("沒有檔案!"); //上傳控制項中如果不包含檔案,退出

// 得到檔案的尾碼
string fileExtension = System.IO.Path.GetExtension(_fileUpload.FileName).ToLower();

// 看包含的檔案是否是被允許的檔案尾碼
fileOK = allowedExtensions.IndexOf(fileExtension) > 0;
if (!fileOK) throw new Exception("不支援的檔案格式!");

//檢查上傳檔案大小
fileOK = AllowMaxSize(_fileUpload.FileBytes.Length);
if (!fileOK) throw new Exception("圖片檔案不能大於" MAX_SIZE_UPLOAD.ToString() "KB!");

try
{
   // 檔案另存在伺服器指定目錄下
   string savefile = GetNewFileName(_savePath, _fileUpload.FileName);
  
   if (IsUploadImage(fileExtension))//儲存圖片
   {
System.Drawing.Image output = CImageLibrary.FromBytes(_fileUpload.FileBytes);

// 檢查圖片寬度/高度/大小
if (this.IMG_MAX_WIDTH != 0 && output.Width > this.IMG_MAX_WIDTH)
{
   output = CImageLibrary.GetOutputSizeImage(output, this.IMG_MAX_WIDTH);
}

Bitmap bmp = new Bitmap(output);

this.CreateDir(Path.GetDirectoryName(savefile));

bmp.Save(savefile, output.RawFormat);
bmp.Dispose();
output.Dispose();

if (_AutoGenWatermark)
{
   WatermarkImage genWatermark = new WatermarkImage();
   genWatermark.DrawWords(savefile, AppConfig.Current.WatermarkMain,
   AppConfig.Current.WatermarkDesc, float.Parse("0.2"));
}
   }
   else//其它任何檔案
   {
this.CreateDir(Path.GetDirectoryName(savefile));

_fileUpload.PostedFile.SaveAs(savefile);
   }
  
   _LastUploadedFile = savefile;
  
   return true;
}
catch (Exception ex)
{
   throw new Exception("上傳檔案時發生未知錯誤!" ex.Message);
}
   }
   catch (Exception ex)
   {
_Error = ex.Message;
return false;
   }
}

private void CreateDir(string dir)
{
   if (Directory.Exists(dir) == false)
   Directory.CreateDirectory(dir);
}

private bool IsUploadImage(string fileExtension)
{
   bool isImage = PICTURE_FILE.IndexOf(fileExtension) > 0;
   return isImage;
}
}
}

上面可以說己完整的介紹了利用 fileupload控制項實現的單個檔案上傳了,如果要多檔案上傳呢怎麼辦?我們接著往下看。

同時上傳多個檔案cs處理代碼
 

 代碼如下 複製代碼
protected void Button1_Click(object sender, EventArgs e)
{
   string filepath = "C:/Uploads";
   //HttpFileCollection類型   HttpFileCollection uploadedFiles = Request.Files;
   
   for (int i = 0; i < uploadedFiles.Count; i++)
   {   
      //HttpPostedFile類型
      HttpPostedFile userPostedFile = uploadedFiles[i];
   
      try
      {   
 if (userPostedFile.ContentLength > 0 )
 {
    Label1.Text += "File #" + (i+1) + "";
    Label1.Text += "File Content Type: " + userPostedFile.ContentType + "";
    Label1.Text += "File Size: " + userPostedFile.ContentLength + "kb";
    Label1.Text += "File Name: " + userPostedFile.FileName + "";
   
    userPostedFile.SaveAs(filepath + "/" + System.IO.Path.GetFileName(userPostedFile.FileName));
    Label1.Text += "Location where saved: " + filepath + "/" + System.IO.Path.GetFileName(userPostedFile.FileName) + "";
 }   
}
catch (Exception Ex)
{   
 Label1.Text += "Error: " + Ex.Message;   
 }   
}   
}

同時多檔案上傳核心代碼是int i = 0; i < uploadedFiles.Count; i++遍曆了,其它的與單檔案上傳沒有區別。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.