1.Net
[HttpPost]
public JsonResult ExportFile()
{
UploadFile _uploadFile = new UploadFile();
try
{
var file = Request.Files[0];
string fileNameEx = Path.GetExtension(file.FileName);
string fileNameTrue = Path.GetFileNameWithoutExtension(file.FileName);
string imgType = Configs.GetValue("ImgType").ToUpper();
if (file == null || string.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
{
_uploadFile.code = -1;
_uploadFile.data = new { src = "" };
_uploadFile.msg = "上传出错!未检测到文件";
return Json(_uploadFile);
}
if (!imgType.Contains(fileNameEx.ToUpper().Replace(".", "")))
{
_uploadFile.code = -1;
_uploadFile.data = new { src = "" };
_uploadFile.msg = "上传出错!图片格式只支持"+ imgType;
return Json(_uploadFile);
}
string filePathName = string.Empty;
string localPath = Server.MapPath("~/Upload/ArticleUploadImg/");
string tmpName = Server.MapPath("~/Upload/ArticleUploadImg/");
var tmp = file.FileName;
var tmpIndex = 0;
while (System.IO.File.Exists(tmpName + tmp))
{
tmp = fileNameTrue + "_" + ++tmpIndex + fileNameEx;
}
filePathName = tmp;
if (!Directory.Exists(localPath))
Directory.CreateDirectory(localPath);
file.SaveAs(Path.Combine(tmpName, filePathName));
_uploadFile.code = 0;
_uploadFile.data = new { src = Path.Combine("/Upload/ArticleUploadImg/", filePathName), title = Path.GetFileNameWithoutExtension(filePathName) };
_uploadFile.msg = "上传成功";
return Json(_uploadFile);
}
catch (Exception ex)
{
return Json(_uploadFile, JsonRequestBehavior.AllowGet);
}
}
2. NetCore
[HttpPost, Route("attachment/Upload")]
public IHttpResponseResult UploadFile()
{
const string logName = "UploadFile";
try
{
var files = HttpContext.Current.Request.Files;
if (files.Count <= 0) return Fail(logName, "未获取到文件");
for (var i = 0; i < files.Count; i++)
{
var file = files[i];
if (file == null) continue;
if (file.ContentLength > 1024 * 1024 * 5)
{
return Fail(logName, $"文件({file.FileName})大小超过5M", ErrorCode.FileTooLarge);
}
}
var fileFolderId = Guid.NewGuid();
for (var i = 0; i < files.Count; i++)
{
var file = files[i];
if (file == null) continue;
var ext = Path.GetExtension(file.FileName).Replace(".", "");
if (Array.IndexOf(AppConfigs.FileType.Split('|'), ext) == -1)
{
return Fail(logName, $"({file.FileName})文件类型不支持", ErrorCode.FileTypeNotSupport);
}
var fileFolderPath = $"{HostingEnvironment.MapPath("/")}{AttachmentsBasePath}/{fileFolderId}/";
if (!Directory.Exists(fileFolderPath))
{
Directory.CreateDirectory(fileFolderPath);
}
var filePath = Path.Combine(fileFolderPath, file.FileName);
file.SaveAs(filePath);
}
return Success(logName, fileFolderId, "文件上传成功");
}
catch (Exception ex)
{
return Fail(logName, $"上传文件异常\n{ex.ToExceptionString()}");
}
}
3.文件操作
public static class FileHelper
{
private static readonly string RootPath = AppDomain.CurrentDomain.BaseDirectory;
public static Dictionary<string, byte[]> ReadBatchFile(string fileFolderName, string path)
{
var fileDic = new Dictionary<string, byte[]>();
var fileFolderPath = GetFolderPath(fileFolderName, path);
if (fileFolderPath.IsNullOrEmpty())
{
return fileDic;
}
var filesPath = GetAllFiles(fileFolderPath);
foreach (var filePath in filesPath)
{
var fileName = filePath.Split('\\').Last();
fileDic.Add(fileName, File.ReadAllBytes(filePath));
}
return fileDic;
}
public static void DeleteDirectory(string fileFolderName, string path)
{
var fileFolderPath = GetFolderPath(fileFolderName, path);
if (fileFolderPath.IsNullOrEmpty()) return;
var filesPath = GetAllFiles(fileFolderPath);
foreach (var filePath in filesPath)
{
File.Delete(filePath);
}
Directory.Delete(fileFolderPath);
}
private static string GetFolderPath(string fileFolderName, string path)
{
return Directory.GetDirectories($"{RootPath}/{path}", fileFolderName,
SearchOption.TopDirectoryOnly).FirstOrDefault();
}
private static IEnumerable<string> GetAllFiles(string fileFolderPath)
{
return Directory.GetFiles(fileFolderPath, "*");
}
public static byte[] ReadSingleFile(string fileName, string path)
{
var filePath = GetExactFilePath(fileName, path);
return filePath.IsNullOrEmpty() ? null : File.ReadAllBytes(filePath);
}
private static string GetExactFilePath(string fileName, string path)
{
return Directory.GetFiles($"{RootPath}/{path}", fileName, SearchOption.AllDirectories).FirstOrDefault();
}
public static void DeleteFile(string fileName, string path)
{
var filePath = GetExactFilePath(fileName, path);
if (!filePath.IsNullOrEmpty()) File.Delete(filePath);
}
public static string[] GetFuzzyFilePath(string fileName, string path)
{
return Directory.GetFiles($"{RootPath}/{path}", $"*{fileName}*.*", SearchOption.AllDirectories);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异