今天闲来无事,就把以前写的上传文件的方法封装了一下,封装后感觉很好用,如果有什么错误还请大家给出指导,下面是代码
首先新建一个类tool
下面是具体封装的方法:
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileUploadControl">上传文件的控件</param>
/// <param name="path">上传的服务器相对路径径 如“~\\Resource\\Images”</param>
/// <param name="arrayType">上传文件的文件格式</param>
/// <param name="errorMessage">返回错误信息</param>
/// <param name="filePath">返回绝对路径</param>
/// <returns>返回值</returns>
public static bool UploadFile(FileUpload fileUploadControl, string path, string[] arrayType, out string errorMessage, out string filePath)
{
if (fileUploadControl.HasFile)
{
string fullFileName = fileUploadControl.PostedFile.FileName;
string fileName = fullFileName.Substring(fullFileName.LastIndexOf("\\") + 1);
string fileType = fileName.Substring(fileName.LastIndexOf('.') + 1);
if (arrayType.Contains(fileType.ToLower()))
{
string basePath = HttpContext.Current.Server.MapPath(path);
string subPath = basePath + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileName;
//这里是给上传文件取个时间+文件名的名字
if (!File.Exists(subPath))
{
if (!Directory.Exists(basePath))
Directory.CreateDirectory(basePath);
filePath = subPath;
errorMessage = string.Empty;
return true;
}
else
{
errorMessage = "您上传的文件已存在,请重命名后再上传!";
filePath = string.Empty;
return false;
}
}
else
{
errorMessage = "您上传的文件格式不正确!";
filePath = string.Empty;
return false;
}
}
else
{
errorMessage = "您未上传文件或上传的文件为空!";
filePath = string.Empty;
return false;
}
}
下面是使用方法(上传按钮的点击事件):
protected void btnupload_Click(object sender, EventArgs e)
{
string errorMessage = string.Empty;
string filePath = string.Empty;
string[] arrayType=new string[]{"jpg","png","jpeg","bmp","gif"};
string path="~\\Resource\\Images";
bool status = tool.UploadFile(this.FileUpload1,path ,arrayType , out errorMessage, out filePath);
if (status)
{
try
{
FileUpload1.PostedFile.SaveAs(filePath);
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('上传成功!')", true);
}
catch (Exception)
{
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('上传失败!')", true);
throw;
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + errorMessage + "');", true);
}
}
OK,好了,这样就可以实现一般上传的功能了