上传文件

public class UploadFile
{
//允许上传文件的扩展名
private List<string> _extensions = new List<string>();
/// <summary>
/// 添加允许上传文件的扩展名
/// </summary>
/// <param name="extension"></param>
public void AddExtension(string extension)
{
_extensions.Add(extension);
}
private int _maxLength = 500 * 1024;
/// <summary>
/// 最大文件大小,单位为k
/// </summary>
public int MaxLength
{
set
{
_maxLength = value;

}
}
private string _virtualPath;
/// <summary>
/// 虚拟路径
/// </summary>
public string VirtualPath
{
set
{
_virtualPath = value;
}

}
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
public UploadFileResponse Upload(HttpPostedFileBase file)
{

UploadFileResponse response = new UploadFileResponse();
//检查设定文件扩展或虚拟路劲
if (_extensions.Count == 0)
{
response.Success = false;
response.Message = "请设定允许上传文件扩展名";
return response;
}
if (string.IsNullOrEmpty(_virtualPath))
{
response.Success = false;
response.Message = "请设定上传文件的虚拟路劲";
return response;
}
try
{
if (file.ContentLength == 0)
{
response.Success = false;
response.Message = "没有选择任何文件";
}
string extension = System.IO.Path.GetExtension(file.FileName);
if (!_extensions.Contains(extension))
{
response.Success = false;
string extensionStr = string.Empty;
_extensions.ForEach(t => extensionStr += t + ",");
response.Message = string.Format("只能上传{0}文件", extensionStr);
}
if (file.ContentLength > _maxLength)
{
response.Success = false;
response.Message = string.Format("只能上传{0}K内的文件", _maxLength);
}
string fileDir = System.Web.HttpContext.Current.Server.MapPath(_virtualPath);
string fileName=Guid.NewGuid() + extension;
//上传文件
file.SaveAs(System.IO.Path.Combine(fileDir, fileName));
response.Success = true;
response.VirtualPath = _virtualPath;
response.ActualPath = fileDir;
response.FileName = fileName;
response.Message = "上传成功";
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.ToString();
}
return response;
}
}

DEMO:

UploadFile uploadFile = new UploadFile();
uploadFile.VirtualPath = "/import/InnerResource";
uploadFile.AddExtension(".xls");
uploadFile.AddExtension(".xlsx");
UploadFileResponse uploadFileResponse = uploadFile.Upload(files[0]);

原文地址:https://www.cnblogs.com/cicada/p/9765764.html