ASP.NET 에서 구현 되 는 간단 한 파일 업로드 클래스
UploadFile uf = new UploadFile();
/* */
uf.SetIsUseOldFileName(true);// ( :true),true ,false
uf.SetFileDirectory(Server.MapPath("/file/temp3/"));// ( :/upload)
uf.SetFileType("*");// , , ! * ( : .pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif )
uf.SetIsRenameSameFile(false);// ?
//
var message = uf.Save(Request.Files["Fileupload1"]); // “/file/temp3/2015/4/xx.jpg”
//
var message2 = uf.Save(Request.Files["Fileupload1"], "001" /* */); // “/file/temp3/001/xx.jpg”
//
var isError = message.Error;//
var webPath = message.WebFilePath;// web
var msg = message.Message;//
var filePath = message.FilePath;//
var isSuccess = message.Error == false;
코드:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
namespace SyntacticSugar
{
/// <summary>
/// ** : ( )
/// ** :2015-5-27
/// ** :-
/// ** :sunkaixuan
/// </summary>
public class UploadFile
{
private ParamsModel Params;
public UploadFile()
{
Params = new ParamsModel()
{
FileDirectory = "/upload",
FileType = ".pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif",
MaxSizeM = 10,
PathSaveType = PathSaveType.dateTimeNow,
IsRenameSameFile=true
};
}
/// <summary>
/// ( :/upload)
/// </summary>
public void SetFileDirectory(string fileDirectory)
{
if (fileDirectory == null)
{
throw new ArgumentNullException("fileDirectory");
}
var isMapPath = Regex.IsMatch(fileDirectory, @"[a-z]\:\\", RegexOptions.IgnoreCase);
if (isMapPath)
{
fileDirectory = GetRelativePath(fileDirectory);
}
Params.FileDirectory = fileDirectory;
}
/// <summary>
/// ( :true)
/// </summary>
/// <param name="isUseOldFileName">true ,false </param>
public void SetIsUseOldFileName(bool isUseOldFileName)
{
Params.IsUseOldFileName = isUseOldFileName;
}
/// <summary>
/// , , ! * ( : .pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif )
/// </summary>
public void SetFileType(string fileType)
{
Params.FileType = fileType;
}
/// <summary>
/// ( :M)
/// </summary>
public void SetMaxSizeM(double maxSizeM)
{
Params.MaxSizeM = maxSizeM;
}
/// <summary>
/// ?
/// </summary>
/// <param name="isRenameSameFile">true: ,false </param>
public void SetIsRenameSameFile(bool isRenameSameFile)
{
Params.IsRenameSameFile = isRenameSameFile;
}
/// <summary>
///
/// </summary>
/// <param name="postFile">HttpPostedFile</param>
/// <returns></returns>
public ResponseMessage Save(HttpPostedFile postFile)
{
return CommonSave(postFile);
}
/// <summary>
/// ,
/// </summary>
/// <param name="postFile">HttpPostedFile</param>
/// <param name="number"> </param>
/// <returns></returns>
public ResponseMessage Save(HttpPostedFile postFile, string number)
{
Params.PathSaveType = PathSaveType.code;
_Number = number;
return CommonSave(postFile);
}
/// <summary>
/// , HttpPostedFile
/// </summary>
/// <param name="postFile">HttpPostedFile</param>
/// <param name="isRenameSameFile"> true ,false </param>
/// <param name="fileName"> </param>
/// <returns></returns>
private ResponseMessage CommonSave(HttpPostedFile postFile)
{
ResponseMessage reval = new ResponseMessage();
try
{
if (postFile == null || postFile.ContentLength == 0)
{
TryError(reval, " !");
return reval;
}
//
string fileName = Params.IsUseOldFileName ? postFile.FileName : DateTime.Now.ToString("yyyyMMddhhmmssms") + Path.GetExtension(postFile.FileName);
//
this.CheckingType(reval, postFile.FileName);
//
this.CheckSize(reval, postFile);
if (reval.Error) return reval;
string webDir = string.Empty;
//
var directory = this.GetDirectory(ref webDir);
var filePath = directory + fileName;
if (System.IO.File.Exists(filePath))
{
if (Params.IsRenameSameFile)
{
filePath = directory + DateTime.Now.ToString("yyyyMMddhhssms") + "-" + fileName;
}
else
{
System.IO.File.Delete(filePath);
}
}
//
postFile.SaveAs(filePath);
reval.FilePath = filePath;
reval.FilePath = webDir + fileName;
reval.FileName = fileName;
reval.WebFilePath = webDir + fileName;
return reval;
}
catch (Exception ex)
{
TryError(reval, ex.Message);
return reval;
}
}
private void CheckSize(ResponseMessage message, HttpPostedFile PostFile)
{
if (PostFile.ContentLength / 1024.0 / 1024.0 > Params.MaxSizeM)
{
TryError(message, string.Format(" , {0}M!", Params.MaxSizeM));
}
}
/// <summary>
///
/// </summary>
/// <param name="fileDirectory"></param>
/// <param name="sever"></param>
/// <returns></returns>
private static string GetRelativePath(string fileDirectory)
{
var sever = HttpContext.Current.Server;
fileDirectory = "/" + fileDirectory.Replace(sever.MapPath("~/"), "").TrimStart('/').Replace('\\', '/');
return fileDirectory;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string GetDirectory(ref string webDir)
{
var sever = HttpContext.Current.Server;
//
string directory = Params.FileDirectory;
//
string childDirectory = DateTime.Now.ToString("yyyy-MM/dd");
if (Params.PathSaveType == PathSaveType.code)
{
childDirectory = _Number;
}
webDir = directory.TrimEnd('/') + "/" + childDirectory + '/';
string dir = sever.MapPath(webDir);
//
if (Directory.Exists(dir) == false)
Directory.CreateDirectory(dir);
return dir;
}
/// <summary>
/// )
/// </summary>
/// <param name="fileName"></param>
private void CheckingType(ResponseMessage message, string fileName)
{
if (Params.FileType != "*")
{
//
string[] typeList = Params.FileType.Split(',');
// ( )
string type = Path.GetExtension(fileName).ToLowerInvariant(); ;
//
if (typeList.Contains(type) == false)
this.TryError(message, " !");
}
}
/// <summary>
///
/// </summary>
/// <param name="Msg"></param>
private void TryError(ResponseMessage message, string msg)
{
message.Error = true;
message.Message = msg;
}
#region models
private class ParamsModel
{
/// <summary>
///
/// </summary>
public string FileDirectory { get; set; }
/// <summary>
/// , , !
/// </summary>
public string FileType { get; set; }
/// <summary>
///
/// </summary>
public double MaxSizeM { get; set; }
/// <summary>
///
/// </summary>
public PathSaveType PathSaveType { get; set; }
/// <summary>
/// ?
/// </summary>
public bool IsRenameSameFile { get; set; }
/// <summary>
///
/// </summary>
public bool IsUseOldFileName { get; set; }
}
/// <summary>
///
/// </summary>
public enum PathSaveType
{
/// <summary>
///
/// </summary>
dateTimeNow = 0,
/// <summary>
/// ID
/// </summary>
code = 1
}
private string _Number { get; set; }
/// <summary>
///
/// </summary>
public class ResponseMessage
{
/// <summary>
///
/// </summary>
public bool Error { get; set; }
/// <summary>
///
/// </summary>
public string Message { get; set; }
/// <summary>
///
/// </summary>
public string FilePath { get; set; }
/// <summary>
///
/// </summary>
public string WebFilePath { get; set; }
/// <summary>
///
/// </summary>
public string FileName { get; set; }
}
#endregion
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
개인간에 최대 2.5GB의 파일을 교환할 수 있는 Firefox Send를 로컬로 사용참고) Firefox Send의 특징은 근본적으로 다음과 같습니다. 디폴트라면 2.5GB까지의 파일 다운로드 URL을 발행할 수 있다. 파일은 암호화되어 관리된다. 보존 기간을 URL 발행시에 설정할 수 있다(5분~...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.