使用UploadiFive上传文件,简单易用


目录
  • 一、前端
    • HTML上传标签部分
    • JavaScript上传部分
    • uploadify-custom文件内容
      • uploadify-custom.css
      • uploadify-custom.js
  • 二、后端
    • 上传接口
      • UploadifyController.cs
    • 关联文件

JQuery上传插件uploadify提供两个版本,flash的uploadify和html5的uploadifive。

uploadify下载地址

下面使用uploadifive,自己创建了UploadifyCustom,对uploadify进行了扩展,在很多上传业务场景中有使用到。

一、前端

HTML上传标签部分

  上传 取消
 

JavaScript上传部分

引入js、css。*-custom 为自定义扩展文件,详情见“uploadify-custom文件内容”








uploadify-custom文件内容

uploadify-custom.css

.uploadify-button {
    background-color: transparent;
    border: none;
    padding: 0;
    text-indent: -9999px;
    height: 30px;
    line-height: 30px;
    width: 120px;
    background-image: url('../images/browse-btn-en.png');
    transform: scale(0.8);
    /*-ms-transform:scale(0.9);
        -webkit-transform:scale(0.9);
        -o-transform:scale(0.9);
        -moz-transform:scale(0.9);*/
}

.uploadify:hover .uploadify-button {
    background-image: url('../images/browse-btn-en.png');
}

/*five*/
.uploadifive-button {
	float: left;
	margin-right: 10px;
    background-image: url('../images/browse-btn-en.png');
}
.uploadifive-button:hover {
    background-image: url('../images/browse-btn-en.png');
}

#queue {
	/*border: 1px solid #E5E5E5;*/	
	overflow: auto;
	margin-bottom: 10px;
	padding: 0 3px 3px;
	/*width: 300px;
    height: 177px;*/
    display:none;
}

.files > *{
    /*display:inline;*/
}

.files > a {
    color: #337ab7;
}

uploadify-custom.js

/*
 * UploadifyCustom v1.2
 * Copyright (c) 2019 Rural
 */

var uploadifyCommon = {};

/**
 * var settingsObj = { urlBasePath, dirName, requestUrlAction, requestUrlFile };
 */
uploadifyCommon.PathSettings = function ({ urlBasePath, urlBasePathFile, dirName, requestUrlAction, requestUrlFile }) {
    this.urlBasePath = urlBasePath; //配置附件站点根路径,如"http://localhost:1802"
    this.urlBasePathFile = urlBasePathFile;
    this.dirName = dirName; //配置文件根目录,如"UploadFiles/AM"
    this.requestUrlAction = requestUrlAction;   //上传请求路径
    this.requestUrlFile = requestUrlFile;   //删除等操作请求路径
};

/**
 * 默认pathSettings
 */
uploadifyCommon.pathSettings = new uploadifyCommon.PathSettings({
    urlBasePath: uploadSettings.urlBasePath,
    urlBasePathFile: uploadSettings.urlBasePathFile,
    dirName: uploadSettings.dirName,
    requestUrlAction: uploadSettings.urlBasePath + "/api/Uploadify/ProcessRequest",
    requestUrlFile: uploadSettings.urlBasePath + "/api/Uploadify/GetFiles"
});

uploadifyCommon.Settings = function (pathSettings) {
    this.pathSettings = pathSettings;

    this.options = {
        auto: false,
        uploader: pathSettings.requestUrlAction,
        uploadType: "five", //flash、five
        controlId: "fileUpload",    //上传控件ID
        queueID: "",
        queueSizeLimit: 2,
        events: {
            onSelect: function () {

            }, onUploadComplete: function (file, data) {

            }
        }
    };

    this.uploadReq = {
        Action: "upload",
        SerialNo: "",   //上传目录编号
        UrlBasePath: pathSettings.urlBasePathFile,
        UrlPartPath: "",
        FileUrl: "",
        BasePath: "",
        DirName: pathSettings.dirName,  //指定目录        
        SubDirName: "", //编号下的子目录
        SubDirNameAsInnermost: pathSettings.SubDirNameAsInnermost || "0",  //SubDirName为最里层目录
        FileType: "file",   //image,flash,media,file,word,excel
        Rename: 0,  //系统是否自动重命名文件
        IsExcel: 0,
        UserId: "" //上传者
    };

    this.linkOptions = {
        data: [],     //文件集合
        accessPermission: 'v',    //v—查看权限,e—编辑权限,h-隐藏
        linkType: 'file',     //file,image
        fileContentId: 'files', //文件内容容器Id
        filePathId: '', //文件路径
        requestUrl: pathSettings.requestUrlAction, //删除等操作请求路径
        hideFileContent: false
    };

};

function generateLink(settings) {
    var pathSettings = settings.pathSettings;
    var linkOptions = settings.linkOptions;
    var res = linkOptions.data || [];
    var accessPermission = linkOptions.accessPermission || "v";
    var linkType = linkOptions.type || "file";
    var fileContentId = linkOptions.fileContentId || "";
    var filePathId = linkOptions.filePathId || "";

    var width = 125;
    var height = 125;
    var filePathObj = $("#" + filePathId);
    var contentObj = $("#" + fileContentId);
    filePathObj.val("");
    contentObj.html("");

    if (res.length > 0) {
        if (filePathId != "") {
            var latestObj = res[0];
            if (linkOptions.hideFileContent) {
                contentObj.hide();
                filePathObj.val(latestObj.FileUrl);
                $("#fileName").text(latestObj.FileName);
            } else {
                filePathObj.val(latestObj.UrlPartPath);
            }
        }

        var htmlStr = "";
        var fileCount = 0;
        var maxCount = 1;
        for (var index in res) {
            var obj = res[index];
            var fileName = obj.FileName;
            var urlBasePath = pathSettings.urlBasePathFile || obj.UrlBasePath;
            var urlPartPath = obj.UrlPartPath || "";
            var fileUrl = obj.FileUrl || "";
            //var url = "http://" + location.host + "/" + fileUrl;
            var url = urlBasePath + "/" + fileUrl;
            //var encodeFileName = encodeURIComponent(fileName);
            //url = url.replace(fileName, encodeFileName);

            var objStr = escape(JSON.stringify(obj));
            //var linkOptionsStr = escape(JSON.stringify(linkOptions));
            var settingsStr = escape(JSON.stringify(settings));
            //var deleteFunc = "deleteFile('" + objStr + "')";
            var deleteFunc = "deleteFile('" + objStr + "','" + settingsStr + "')";
            fileCount++;

            var partStr = "";
            if (linkType == "image") {
                partStr = "";
            } else {
                partStr = fileName;
            }

            if (accessPermission == "e") {
                if (fileCount == maxCount) {
                    htmlStr += "" + partStr + "  删除
"; fileCount = 0; } else { htmlStr += "" + partStr + "  删除  "; } } else if (accessPermission == "v") { if (fileCount == maxCount) { htmlStr += "" + partStr + "
"; fileCount = 0; } else { htmlStr += "" + partStr + " "; } } } contentObj.html(htmlStr); } else { console.log("no"); } } function deleteFile(objStr, settingsStr) { var obj = JSON.parse(unescape(objStr)); var settings = JSON.parse(unescape(settingsStr)); //var pathSettings = settings.pathSettings; var req = settings.uploadReq; req.Action = "delete"; $.extend(req, obj); //console.log(req); //var req = { // Action: "delete", // SerialNo: "", //上传目录编号 // UrlBasePath: "", // UrlPartPath: "", // FileUrl: "", // BasePath: "", // UserId: "" //}; var formData = new FormData(); for (var key in req) { formData.append(key, req[key]); } if (confirm("确认删除吗?")) { $.ajax({ type: "POST", url: settings.linkOptions.requestUrl, //data: req, data: formData, contentType: false, processData: false, dataType: "json", //async: false, success: function (data) { settings.linkOptions.data = data.Result; generateLink(settings); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); //alert(XMLHttpRequest.readyState); //alert(textStatus); } }); } } function uploadifyInitialize(settings, generateLink) { var options = settings.options; var uploadReq = settings.uploadReq; var linkOptions = settings.linkOptions; var uploader = $('#' + options.controlId); if (options.uploadType == "flash") { uploader.uploadify({ auto: false, height: 30, swf: '/rural/js/bll/common/uploadify/uploadify-swf/uploadify.swf', uploader: options.uploader, width: 120, //method:"get", formData: options, onCancel: function (file) { //alert('The file ' + file.name + ' was cancelled.'); }, onUploadSuccess: function (file, data, response) { //console.log(data); var res = JSON.parse(data); if (res.Code != 200) { alert(res.Message); } if (generateLink) { settings.linkOptions.data = res.Result; generateLink(settings); } }, 'onFallback': function () { alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。"); }, 'onSelectError': function (file, errorCode, errorMsg) { var msgText = "上传失败\n"; switch (errorCode) { case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: //var towedAccreditDivLen = $("#towedAccreditDiv").children().length; msgText += "每次最多上传 " + uploader.uploadify('settings', 'uploadLimit') + "个文件"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: msgText += "文件大小超过限制( " + uploader.uploadify('settings', 'fileSizeLimit') + " )"; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: msgText += "文件大小为0"; break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: msgText += "文件格式不正确,仅限 " + uploader.uploadify('settings', 'fileTypeExts'); break; default: msgText += "错误代码:" + errorCode + "\n" + errorMsg; } alert(msgText); }, 'onUploadError': function (file, errorCode, errorMsg, errorString) { switch (errorCode) { case -100: alert("上传的文件数量已经超出系统限制的" + uploader.uploadify('settings', 'queueSizeLimit') + "个文件!"); break; case -110: alert("文件 [" + file.name + "] 大小超出系统限制的" + uploader.uploadify('settings', 'fileSizeLimit') + "大小!"); break; case -120: alert("文件 [" + file.name + "] 大小异常!"); break; case -130: alert("文件 [" + file.name + "] 类型不正确!"); break; } } }); } else { if (options.queueID == undefined || options.queueID == "") { options.queueID = "queue"; } $('#' + options.queueID).show(); uploader.uploadifive({ 'auto': options.auto, //'checkScript': '', 'formData': uploadReq, 'method': 'post', //'queueID': 'queue', 'queueID': options.queueID, 'removeCompleted': true, 'buttonText': '', 'uploadScript': options.uploader, 'fileSizeLimit': "120MB",//上传文件大小限制数,如:1024KB、5MB 'queueSizeLimit': options.queueSizeLimit, //'uploadLimit': 2, //有bug //'width': 100, //按钮宽度 //'height': 30, //按钮高度 'onUploadComplete': function (file, data) { //console.log(data); var res = JSON.parse(data); if (res.Code != 200) { alert(res.Message); } if (generateLink) { settings.linkOptions.data = res.Result; generateLink(settings); } if (options.events.onUploadComplete) { options.events.onUploadComplete(file, data); } }, 'onFallback': function (res) { //alert("the HTML5 File API is not supported by the browser."); alert(res); }, //'onError': function (res) { // alert(res); //}, 'onSelect': function () { if (options.events.onSelect) { options.events.onSelect(); } }, 'onError': function (errorType, file, data) { var msgText = "上传失败:"; switch (errorType) { case "QUEUE_LIMIT_EXCEEDED": //var towedAccreditDivLen = $("#towedAccreditDiv").children().length; msgText += "最多能上传 " + uploader.data('uploadifive').settings.queueSizeLimit + "个文件"; break; case "UPLOAD_LIMIT_EXCEEDED": msgText += "最多能上传 " + uploader.data('uploadifive').settings.uploadLimit + "个文件"; break; case "FILE_SIZE_LIMIT_EXCEEDED": msgText += "最多能上传 " + uploader.data('uploadifive').settings.fileSizeLimit / (1.024 * 1000000) + "M"; break; default: msgText += errorType; } alert(msgText); } }); } } function upload(controlId, uploadType) { if (uploadType == undefined) { uploadType = "five"; } doUplaod(controlId, 0, uploadType); } function cancel(controlId, uploadType) { if (uploadType == undefined) { uploadType = "five"; } closeLoad(controlId, uploadType); } function doUplaod(controlId, action, type) { var uploader = $('#' + controlId); var len = 0; if (type == "flash") { len = uploader.data('uploadify').queueData.queueLength; if (len <= 0) { alert("请先选择要上传的文件"); } if (action == 1) { uploader.uploadify('upload'); } else { uploader.uploadify('upload', '*'); } } else { len = uploader.data('uploadifive').queue.count; if (len <= 0) { alert("请先选择要上传的文件"); } if (action == 1) { uploader.uploadifive('upload'); } else { //uploader.uploadifive('upload', '*'); uploader.uploadifive('upload'); } } } function closeLoad(controlId, type) { var uploader = $('#' + controlId); if (type == "flash") { uploader.uploadify('cancel', '*'); } else { //uploader.uploadifive('cancel', $('.uploadifive-queue-item').first().data('file')); $('.uploadifive-queue-item').map(function (i, obj) { uploader.uploadifive('cancel', $(obj).data('file')); }); } }

二、后端

上传接口

UploadifyController.cs

/// 
    /// uploadify 文件上传
    /// 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [EnableCors("RuralCors")]
    public class UploadifyController : ControllerBase
    {
        HrService _userService;
        IHostingEnvironment _hostingEnvironment;

        public UploadifyController(IAuth authUtil, HrService userService
            , IHostingEnvironment hostingEnvironment)
        {
            _userService = userService;
            _hostingEnvironment = hostingEnvironment;
        }

        private string GetBasePath()
        {
            string basePath = _hostingEnvironment.WebRootPath;
            //string basePath = _hostingEnvironment.ContentRootPath;

            return basePath;
        }

        private List GetFileList(string urlPartPath, string urlBasePath = "")
        {
            UploadReq uploadReq = new UploadReq();
            uploadReq.UrlBasePath = urlBasePath;
            uploadReq.UrlPartPath = urlPartPath;
            string basePath = GetBasePath();

            if (string.IsNullOrWhiteSpace(uploadReq.BasePath))
            {
                uploadReq.BasePath = basePath;
            }
            if (string.IsNullOrWhiteSpace(uploadReq.UrlBasePath))
            {
                uploadReq.UrlBasePath = $"{Request.Scheme}://{Request.Host.Value}";
            }
            
            string filePath = Path.Combine(uploadReq.BasePath, uploadReq.UrlPartPath);
            var uploadResList = FileService.GetFileList(filePath, uploadReq.UrlBasePath, uploadReq.UrlPartPath);

            return uploadResList;
        }

        [HttpPost]
        public string GetFiles([FromForm]string urlPartPath, [FromForm]string urlBasePath = "")
        {
            var list = GetFileList(urlPartPath, urlBasePath);

            return JsonHelper.Instance.Serialize(list);
        }

        [HttpPost]
        [RequestSizeLimit(150_000_000)]
        public string ProcessRequest(IFormCollection formCollection)
        {
            formCollection = formCollection ?? Request.Form;
            UploadReq uploadReq = new UploadReq();

            foreach (var item in formCollection)
            {
                object value = item.Value.FirstOrDefault();
                uploadReq.SetPropertyValue(item.Key, value);
            }

            Response> res = new Response>();

            string basePath1 = AppContext.BaseDirectory;
            string basePath = GetBasePath();

            if (string.IsNullOrWhiteSpace(uploadReq.BasePath))
            {
                uploadReq.BasePath = basePath;
            }

            if ("delete".Equals(uploadReq.Action))
            {
                res = Delete(uploadReq);
            }
            else if ("upload".Equals(uploadReq.Action))
            {
                res = Upload(uploadReq);
            }

            return Serialize(res);
        }

        private Response> Upload(UploadReq uploadReq)
        {
            Response> res = new Response>();

            if (!string.IsNullOrWhiteSpace(uploadReq.DirName))
            {
                try
                {
                    res = UploadFile(uploadReq);
                }
                catch (Exception ex)
                {
                    res.Code = 500;
                    res.Message = "上传失败:" + ex.Message;
                }
            }
            else
            {
                res.Code = 500;
                res.Message = "DirName不能为空";
            }

            return res;
        }

        private Response> Delete(UploadReq uploadReq)
        {
            Response> res = new Response>();
            if (!string.IsNullOrWhiteSpace(uploadReq.FileUrl))
            {
                try
                {
                    string fileFullName = Path.Combine(uploadReq.BasePath, uploadReq.FileUrl);
                    FileService.DeletePath(fileFullName, PathType.File);

                    var uploadResList = GetFileList(uploadReq.UrlPartPath, uploadReq.UrlBasePath);
                    if (uploadResList.Count == 0)
                    {
                        string filePath = Path.Combine(uploadReq.BasePath, uploadReq.UrlPartPath);
                        FileService.DeletePath(filePath, PathType.Directory);
                    }
                    res.Result = uploadResList;
                }
                catch (Exception ex)
                {
                    res.Code = 500;
                    res.Message = "删除失败:" + ex.Message;
                }
            }
            else
            {
                res.Code = 500;
                res.Message = "FileUrl不能为空";
            }

            return res;
        }

        private Response> UploadFile(UploadReq uploadReq)
        {
            Response> res = new Response>();

            HttpContext context = HttpContext;
            string msg = "";
            string serialNo = uploadReq.SerialNo ?? "";
            if (serialNo.Length == 0)
            {
                msg = "请指定SerialNo";
            }
            //var files = context.Request.Files.GetMultiple("Filedata");
            var files = Request.Form.Files.GetFiles("Filedata");

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,mp4,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,csv,ppt,htm,html,txt,zip,7z,rar,gz,bz2,ppt,pptx,mp3,mp4,pdf");
            extTable.Add("word", "doc,docx");
            extTable.Add("excel", "xlsx,xls");
            //HttpPostedFile file = context.Request.Files["Filedata"];

            int validCount = 0;

            if (files.Count > 0)
            {
                string basePath = uploadReq.BasePath ?? "";
                string fileType = uploadReq.FileType ?? "";
                string dirName = uploadReq.DirName ?? "";
                string subDirName = uploadReq.SubDirName ?? "";
                dirName = dirName.Trim('/').Trim('\\');

                string urlPartPath = dirName + "/" + subDirName + "/" + DateTime.Now.ToString("yyyy") + "/" + serialNo;
                string partPath = dirName + "\\" + subDirName + "\\" + DateTime.Now.ToString("yyyy") + "\\" + serialNo;
                if (uploadReq.SubDirNameAsInnermost == "1")
                {
                    urlPartPath = dirName + "/" + DateTime.Now.ToString("yyyy") + "/" + serialNo + "/" + subDirName;
                    partPath = dirName + "\\" + DateTime.Now.ToString("yyyy") + "\\" + serialNo + "\\" + subDirName;
                }

                string filePath = basePath + "\\" + partPath;

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                List errorList = new List();
                List errorListTemp = new List();

                int uploadLimit = 10;
                if (files.Count > uploadLimit)
                {
                    msg = "附件数量不能超过" + uploadLimit;
                    errorListTemp.Add(msg);
                }

                int maxMB = 1024;
                int maxFilesSize = maxMB * 1024;
                var filesLength = files.Select(x => x.Length / 1024).Sum();
                if (filesLength > maxFilesSize)
                {
                    msg = "附件不能超过" + maxMB.ToString() + "MB";
                    errorListTemp.Add(msg);
                }

                foreach (var f in files)
                {
                    if (f.Length >= 0)
                    {
                        validCount++;
                    }
                    else
                    {
                        continue;
                    }

                    errorListTemp.Clear();

                    #region file

                    var file = f;
                    string fileName = file.FileName;
                    string extension = Path.GetExtension(fileName).ToLower();

                    if (!string.IsNullOrEmpty(fileType))
                    {
                        var extlist = new List();
                        foreach (var str in fileType.SplitAndRemove(","))
                        {
                            extlist.AddRange(((string)extTable[str]).SplitAndRemove(","));
                        }

                        if (string.IsNullOrEmpty(extension) || Array.IndexOf(extlist.ToArray(), extension.Substring(1).ToLower()) == -1)
                        {
                            msg = string.Format("“{0}”上传文件失败,可上传文件扩展名为“{1}”", fileName, (string)extTable[fileType]);
                            errorListTemp.Add(msg);
                        }
                    }
                    else
                    {
                        errorListTemp.Add("请指定FileType");
                    }

                    float fileSize = Convert.ToSingle(file.Length) / 1024;
                    //string sizeStr = string.Format("{0:N0}", fileSize);
                    string sizeStr = Math.Round(fileSize, 1, MidpointRounding.ToEven).ToString();

                    int maxSize = maxMB * 1024;

                    if (fileSize > maxSize)
                    {
                        msg = "附件不能超過" + maxMB.ToString() + "MB";
                        errorListTemp.Add(msg);
                    }

                    string fileFullName = string.Empty;
                    if (uploadReq.IsExcel == "1")
                    {

                    }
                    else
                    {
                        string rename = uploadReq.Rename ?? "";

                        if (string.IsNullOrWhiteSpace(rename))
                        {
                            msg = "Rename参数为必填";
                            errorListTemp.Add(msg);
                        }

                        if (rename == "0")
                        {
                            if (!string.IsNullOrWhiteSpace(serialNo))
                            {
                                fileFullName = Path.Combine(filePath, fileName);

                                if (System.IO.File.Exists(fileFullName))
                                {
                                    msg = "该文件已存在,请重新上传";
                                    errorListTemp.Add(msg);
                                }
                            }
                        }
                        else if (rename == "1")
                        {
                            //DataTable dt = GetAttachmentInfo(serialNo);
                            //DataRow[] drArr = dt.Select("fileName='" + fileName + "'");
                            //if (drArr.Length > 0)
                            //{
                            //    msg = "已上传过该附件名";
                            //    errorListTemp.Add(msg);
                            //}

                            string newFileName = string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), extension);
                            fileFullName = Path.Combine(filePath, newFileName);
                        }

                        if (string.IsNullOrEmpty(fileFullName))
                        {
                            msg = "上传文件指定路径不能为空";
                            errorListTemp.Add(msg);
                        }

                        if (errorListTemp.Count == 0)
                        {
                            try
                            {
                                using (var fileStream = new FileStream(fileFullName, FileMode.Create))
                                {
                                    file.CopyTo(fileStream);
                                }
                            }
                            catch (Exception ex)
                            {
                                errorList.Add(string.Format("“{0}”上传失败:{1}", fileName, ex.Message));
                            }
                        }
                        else
                        {
                            errorList.Add(string.Format("“{0}”上传失败:{1}", fileName
                                , string.Join("\\n", errorListTemp)));
                        }
                    }

                    #endregion
                }

                if (validCount == 0)
                {
                    errorList.Add("未找要到上传的文件");
                }

                if (errorList.Count > 0)
                {
                    res.Code = 500;
                    res.Message = string.Join("\\n", errorList);
                }

                var uploadResList = GetFileList(urlPartPath, uploadReq.UrlBasePath);
                res.Result = uploadResList;

                return res;
            }
            else
            {
                msg = "未找到上传文件";
                res.Code = 500;
                res.Message = msg;

                return res;
            }
        }


        private string Serialize(object obj)
        {
            return JsonHelper.Instance.Serialize(obj);
        }
    }

关联文件


//上传请求UploadReq.cs
public class UploadReq
{
    public string Action { get; set; }

    public string SerialNo { get; set; }

    public string UrlBasePath { get; set; }

    public string UrlPartPath { get; set; }

    public string FileUrl { get; set; }

    public string BasePath { get; set; }

    public string DirName { get; set; }

    public string SubDirName { get; set; }

    public string SubDirNameAsInnermost { get; set; }

    public string FileType { get; set; }

    /// 
    /// 0:否,1:是
    /// 
    public string Rename { get; set; }

    /// 
    /// 0:否,1:是
    /// 
    public string IsExcel { get; set; }

    public string UserId { get; set; }
}

//上传响应 UploadRes.cs
public class UploadRes
{
    public string PartPath { get; set; }

    public string UrlBasePath { get; set; }

    public string UrlPartPath { get; set; }

    public string FileName { get; set; }

    public string FileUrl { get; set; }

    public DateTime CreationTime { get; set; }
}

//文件操作服务类 FileService.cs
public class FileService
{
    public static List GetFileList(string filePath, string urlBasePath, string urlPartPath)
    {
        List uploadResList = new List();
        if (!string.IsNullOrWhiteSpace(urlPartPath))
        {
            if (urlPartPath.EndsWith("/") == false)
            {
                urlPartPath = urlPartPath + "/";
            }

            //string[] fileNameArr = Directory.GetFiles(filePath);
            DirectoryInfo folder = new DirectoryInfo(filePath);

            if (folder != null)
            {
                if (folder.Exists)
                {
                    FileInfo[] fiArr = folder.GetFiles().Where(x => x.Extension.Contains("db") == false).ToArray(); ;

                    foreach (FileInfo fi in fiArr)
                    {
                        UploadRes uploadRes = new UploadRes();
                        uploadRes.UrlBasePath = urlBasePath;
                        uploadRes.UrlPartPath = urlPartPath;
                        uploadRes.FileName = fi.Name;
                        uploadRes.FileUrl = string.Format("{0}{1}", uploadRes.UrlPartPath, uploadRes.FileName);
                        uploadRes.CreationTime = fi.CreationTime;
                        uploadResList.Add(uploadRes);
                    }
                }
            }
        }
        var list = uploadResList.OrderByDescending(x => x.CreationTime).ToList();

        return list;
    }

    public static void DeletePath(string path, PathType pathType)
    {
        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }
        else if (pathType == PathType.Directory)
        {
            if (Directory.Exists(path))
            {
                Directory.Delete(path);
            }
        }
    }

}

以上部分如果对你有帮助,欢迎点赞支持。如果有疑问,可以留言评论或者私信我。