asp.net(c#)同时上传多个文件
以下是简单的修改代码
public class UploadFile
{
private string FilePath_m = "upload_img/";
private string fileType = null;
private int fileSize = 0;
/// 初始化变量
public UploadFile()
{
//filePath = "upload_img/"; //上传路径
fileType = "jpg|gif|bmp"; //允许上传的文件类型
fileSize = 200; //允许上传的文件大小
}
public string FilePath
{
set { FilePath_m = value; }
get { return FilePath_m; }
}
public int FileSize
{
set { fileSize = value * 1024; }
get { return fileSize; }
}
public string FileType
{
set { fileType = value; }
get { return fileType;}
}
private string uploadFilePath_m;
public string uploadFilePath
{
set { uploadFilePath_m = value; }
get { return uploadFilePath_m;}
}
/// 上传图片
/// 上传控件名称
/// 是否以当前时间创建文件夹,1为创建,2为指定
/// 返回上传图片的文件名
public string Upload(System.Web.UI.HtmlControls.HtmlInputFile InputFileName,int DirectoryFlag)
{
try
{
//获得客户端文件的路径
string SourceFile = InputFileName.Value.Trim();
if ((SourceFile == string.Empty) || (SourceFile == null))
{
return null;
}
//获得文件扩展名
//string upFileType = SourceFile.Substring(SourceFile.LastIndexOf(".")+1);
string upFileName = InputFileName.PostedFile.FileName;
string upFileType = System.IO.Path.GetExtension(upFileName).ToLower();
string upFileType2 = upFileType.Substring(1,upFileType.Length-1); //去除扩展名中的点
//获得上传文件的大小
long upfileSize = InputFileName.PostedFile.ContentLength;
//检测上传文件格式
string[] arrFileType = fileType.Split('|');
bool allowFlag = false;
foreach(string fileTypeItem in arrFileType)
{
if(fileTypeItem == upFileType2)
{
allowFlag = true ;
break;
}
}
if(!allowFlag)
{
message("文件格式不正确,目前支持的格式为:"+fileType);
return null;
}
//判断上传文件大小
if(upfileSize > fileSize)
{
message("上传的图片不能大于" + (fileSize/1024) + "KB");
return null;
}
//以当前时间保存图片的名字或创建文件夹的名字
string RandomFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + GetRandom(4);
//获得站点的物理路径
//如果为true则以当前时间创建文件夹,否则为设置的文件夹
if (DirectoryFlag == 1)
{
this.uploadFilePath_m = System.Web.HttpContext.Current.Server.MapPath(".") + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
}
else
{
this.uploadFilePath_m = System.Web.HttpContext.Current.Server.MapPath(".") + "/" + this.FilePath ;
}
System.IO.DirectoryInfo upDirectory = new System.IO.DirectoryInfo(uploadFilePath);
//判断文件夹是否存在,不存在则创建
if(!upDirectory.Exists)
{
upDirectory.Create();
}
string fileName = RandomFileName + upFileType;
//this.FilePath = this.uploadFilePath + fileName;
InputFileName.PostedFile.SaveAs(this.uploadFilePath + fileName);
return fileName;
}
catch
{
//异常
message("系统错误,上传失败!");
return null;
}
}
private string GetRandom(int NumberLen)
{
//Create a new Random class
Random myRandom = new Random();
string myRandomNumber = string.Empty;
for (int i=0;i<NumberLen;i++)
{
int RandomNumber = myRandom.Next(9);
myRandomNumber += RandomNumber;
}
return myRandomNumber;
}
private void message(string msg)
{
System.Web.HttpContext.Current.Response.Write(msg);
}
}
浙公网安备 33010602011771号