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

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

uploadify下载地址

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

一、前端

HTML上传标签部分

<div class="row">
    <div class="col-md-4">
        <div class="form-group">
            <div class="col-md-4 formTitle"><label for="">附件</label></div>
            <div class="col-md-8">
                <input type="hidden" id="Attachment" name="Attachment" />
                <table cellpadding="0" style="width:90%;display:none">
                    <tr>
                        <td style="padding:0px;line-height:30px;vertical-align:top">
                            <input id="fileUpload" name="fileUpload" type="file">
                        </td>
                        <td style="padding:0px;line-height:30px;vertical-align:top">
                            <span>
                                &nbsp;
                                <a href="javascript:upload('fileUpload')">上传&nbsp;</a>
                                |&nbsp;
                                <a href="javascript:cancel('fileUpload')">取消</a>
                            </span>
                        </td>
                        <td colspan="4"></td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td colspan="6"></td>
                    </tr>
                </table>
                <div id="queue"></div>
                <div id="files" class="files"></div>
            </div>
        </div>
    </div>
</div>

JavaScript上传部分

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

<script src="~/vendors/jquery/dist/jquery.min.js"></script>
<link href="~/js/bll/common/uploadify/uploadifive/uploadifive.css" rel="stylesheet" />
<script src="~/js/bll/common/uploadify/uploadifive/jquery.uploadifive.min.js"></script>
<link href="~/js/bll/common/uploadify/uploadify-custom/uploadify-custom.css" rel="stylesheet" />
<script src="~/js/bll/common/uploadify/uploadify-custom/uploadify-custom.js"></script>

<script type="text/javascript">

    /**
     serialNo:文件目录流水号
     accessPermission:v—查看权限,e—编辑权限,h-隐藏
     hideUploader:true-隐藏,false-显示
     async:true-异步,false-同步
     events:回调事件,例如:浏览文件后“onSelect”,上传完成“onUploadComplete”,
     */
    var events = {
        onUploadComplete: function (file, data) {
            //上传完成后要做的事
        }
    };
    setAttachmentInfo("20210319140317956", "e", false, true, events);

    //将<input id="fileUpload" type="file">渲染为Uploadify
    function setAttachmentInfo(serialNo, accessPermission, hideUploader, async, events) {
        var fileInfoSettings = {
            controlId: 'fileUpload',
            queueId: '',
            filePathId: 'Attachment',
            fileContentId: 'files',
            accessPermission: accessPermission, //v—查看权限,e—编辑权限,h-隐藏
            hideUploader: hideUploader, //true-隐藏,false-显示
            serialNo: serialNo, //子目录下流水号目录,用来存放文件
            subDirName: 'IDInfo',  //上传文件根目录下的子目录
            fileType: "file,image",
            events: events //回调事件
        };
        setFileInfo(fileInfoSettings, async);
    }

    //初始化默认配置
    function setFileInfo(fileInfoSettings, async) {
        //初始化默认配置,同一页面可存在使用多个上传控件
        var uploaderSettings = new uploadifyCommon.Settings(uploadifyCommon.pathSettings);

        uploaderSettings.options.controlId = fileInfoSettings.controlId;
        uploaderSettings.options.queueID = fileInfoSettings.queueId;
        uploaderSettings.options.events = fileInfoSettings.events;

        uploaderSettings.linkOptions.filePathId = fileInfoSettings.filePathId;
        uploaderSettings.linkOptions.fileContentId = fileInfoSettings.fileContentId;
        uploaderSettings.linkOptions.accessPermission = fileInfoSettings.accessPermission;

        uploaderSettings.uploadReq.SerialNo = fileInfoSettings.serialNo;
        uploaderSettings.uploadReq.SubDirName = fileInfoSettings.subDirName;
        if (fileInfoSettings.fileType) {
            uploaderSettings.uploadReq.FileType = fileInfoSettings.fileType;
        }

        if (uploaderSettings.linkOptions.accessPermission != "h") {
            if (fileInfoSettings.hideUploader == false) {
                var $controlId = $("#" + uploaderSettings.options.controlId);
                if ($controlId != undefined) {
                    $controlId.parents('table').show();
                }
                uploadifyInitialize(uploaderSettings, generateLink);
            }
            if (fileInfoSettings.filePathId != undefined) {
                var filePath = $.byId(fileInfoSettings.filePathId).val() || "";
                if (filePath.length > 0) {
                    getFiles(filePath, generateLink, uploaderSettings, async);
                }
            }
        }
    }

    getFiles = function (urlPartPath, func, uploadifySettings, async) {
        var ret = undefined;
        if (async != false) {
            async = true;
        }

        $.ajax({
            type: "POST",
            url: uploadifySettings.pathSettings.requestUrlFile,
            data: { urlPartPath, urlBasePath: uploadifySettings.pathSettings.urlBasePathFile },
            dataType: "json",
            async: async,
            success: function (data) {
                ret = data;
                if (func) {
                    uploadifySettings.linkOptions.data = data;
                    func(uploadifySettings);
                }
            }
        });

        return ret;
    }

</script>

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 = "<img title='" + fileName + "' src='" + url + "'  width='" + width + "' height='" + height + "'/>";
            } else {
                partStr = fileName;
            }

            if (accessPermission == "e") {
                if (fileCount == maxCount) {
                    htmlStr += "<a target='_bank' href='" + url + "'>" + partStr + "</a>&nbsp; <a style='cursor:pointer;color:red' onclick=" + deleteFunc + " >删除</a><br/>";
                    fileCount = 0;
                } else {
                    htmlStr += "<a target='_bank' href='" + url + "'>" + partStr + "</a>&nbsp; <a style='cursor:pointer;color:red' onclick=" + deleteFunc + " >删除</a>&nbsp;&nbsp;";
                }
            } else if (accessPermission == "v") {
                if (fileCount == maxCount) {
                    htmlStr += "<a target='_bank' href='" + url + "'>" + partStr + "</a><br/>";
                    fileCount = 0;
                } else {
                    htmlStr += "<a target='_bank' href='" + url + "'>" + partStr + "</a>&nbsp;";
                }
            }
        }
        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

/// <summary>
    /// uploadify 文件上传
    /// </summary>
    [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<UploadRes> 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<List<UploadRes>> res = new Response<List<UploadRes>>();

            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<List<UploadRes>> Upload(UploadReq uploadReq)
        {
            Response<List<UploadRes>> res = new Response<List<UploadRes>>();

            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<List<UploadRes>> Delete(UploadReq uploadReq)
        {
            Response<List<UploadRes>> res = new Response<List<UploadRes>>();
            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<List<UploadRes>> UploadFile(UploadReq uploadReq)
        {
            Response<List<UploadRes>> res = new Response<List<UploadRes>>();

            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<string> errorList = new List<string>();
                List<string> errorListTemp = new List<string>();

                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<string>();
                        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; }

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

    /// <summary>
    /// 0:否,1:是
    /// </summary>
    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<UploadRes> GetFileList(string filePath, string urlBasePath, string urlPartPath)
    {
        List<UploadRes> uploadResList = new List<UploadRes>();
        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);
            }
        }
    }

}

posted @ 2022-03-19 15:36  prestlei  阅读(1137)  评论(0)    收藏  举报