一聚教程网:一个值得你收藏的教程网站

热门教程

.Net中FileUpload控件文件上传与验证实用例子

时间:2022-06-25 03:39:21 编辑:袖梨 来源:一聚教程网

最简单的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("");
}
catch
{
Response.Write("");
}
}
else
{
Response.Write("");
}
}

上面的没做文件大小判断只做了图片类型了,如果要判断大小我们需要如下设置

在web.config中配置:

 代码如下 复制代码


 
 psd|.svg|"/>
 

在.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
{
///


/// 支持上传的文件类型
///

public enum UploadFileType
{
ArticleAttachment = 1,
Image = 2,
Video = 3,
All = 4
}
  
///
/// 上传文件管理类
///

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的文件。

///


/// 构造器
///

/// Asp.net FileUpload对象
/// 保存目录,不包含文件名
/// 自动生成文件名
public CFileUpload(FileUpload fileUpload, string savePath, bool autoGenFileName, bool autoGenWatermark)
{
   _savePath = savePath;
   _fileUpload = fileUpload;
   _AutoGenFileName = autoGenFileName;
   _AutoGenWatermark = autoGenWatermark;
}

///


/// 构造器
///

/// Asp.net FileUpload对象
/// 保存目录,不包含文件名
public CFileUpload(FileUpload fileUpload, string savePath)
{
   _savePath = savePath;
   _fileUpload = fileUpload;
}

///


/// 上传RAR文件
///

public bool UploadRARFile()
{
   return DoUpload(ZIP_FILE);
}

///


/// 上传视频文件
///

public bool UploadVideo()
{
   return DoUpload(MUILT_MEDIA_FILE);
}

///


/// 上传图片文件
///

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);
}

///


/// 上传任何支持的文件
///

public bool UploadAnySupported()
{
   return DoUpload(PICTURE_FILE ZIP_FILE MUILT_MEDIA_FILE);
}

///


/// 生成新的文件名
///

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;
   }
}

///


/// 最大支持小于1MB的文件。
///

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++遍历了,其它的与单文件上传没有区别。

热门栏目