多附件上传

//1,       
<tr>
                <td class="fieldTitle3"></td>
                <td colspan="5" class="fujianDiv" style="padding-right: 40px;">
                    <input class="button01" type="button" id="btnUpFile" name="btnUpFile" value="上传附件" style="cursor: pointer;" onclick="ShowUploadFileView(); return false;" />                  
                </td>
            </tr>  
               <tr>
                <td colspan="4" class="fujianDiv" style="text-align: initial;">
                    <iframe id="uploadFile" name="uploadFile" src="/Inf_Train/AnnexView?instanceid=&type=InfTrain&appid=@Request.QueryString["appid"]" style="width:850px;border:none;"></iframe>
                </td>
            </tr> 


  //上传文件 
          function ShowUploadFileView()
          {
              //弹框实现
            //dialog.open({ id: "window_" + appid.replaceAll('-', ''), title: "上传文件", width: 600, height: 200, url: top.rootdir + '/Inf_Train/UploadFileView?' + query, openerid: iframeid });
              dialog.open({ id: "window_" + appid.replaceAll('-', ''), title: "上传文件", width: 600, height: 200, url: top.rootdir + '/Inf_Train/UploadFileView?_=&type=add&' + query, openerid: iframeid });
          }
//2
@{
    ViewBag.Title = "InfTrain_InfTrain_Upload";
}

<form method="post" id="UploadFileForm" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    <br />
    <table cellpadding="0" cellspacing="1" border="0" width="99%" class="formtable">
        <tr>
            <th style="width: 80px;">文件类型:</th>
            <td>
                <select style="width: 130px;" class="myselect" name="txtFileType" style="margin-right: 5px">
                    @{
                        Data.MSSQL.Dictionary dic = new Data.MSSQL.Dictionary();
                        var dict3 = dic.GetByCode("pxFile");
                        if (dict3 != null)
                        {
                            IList<Dictionary> useStateList = dic.GetChilds(dict3.ID);
                            foreach (var item in useStateList)
                            {
                        <option value="@item.Value">@item.Title</option>
                            }
                        } 
                    }
                </select>
            </td>
        </tr>
        @* <tr>
            <th style="width: 80px;">文件名称:</th>
            <td>
                <input type="text" id="txtFileName" name="txtFileName" value="" class="mytext" style="width: 75%;" validate="empty" /></td>
        </tr>*@
        <tr>
            <th style="width: 80px;">选择文件:</th>
            <td>
                 <input class="text1" type="file" multiple="multiple" style="width:75%;height:24px;" value="" id="selectFile" name="selectFile">
            </td>
        </tr>
    </table>
    <div class="buttondiv">
        <input type="submit" value="确定保存" class="mybutton"  id="btnSave" name="btnaSave"/>
        <input type="button" value="取消关闭" class="mybutton" onclick="CloseForm();" id="btnCancel" name="btnCancel" />
    </div>
</form>
<script type="text/javascript">
    var win = new RoadUI.Window();
    function CloseForm() {
        win.close();
        return false;
    }  
    $(function () {
        @Html.Raw(ViewBag.Script)
    });
</script>

<table cellpadding="0" cellspacing="1" border="0" width="100%" class="listtable" style="text-align: center; text-align: center;" name="tbFiles">
    <thead>
        <tr>
            <th style="text-align: center; width: 60px;">
                <input type="checkbox" onclick="checkAll(this.checked);" style="vertical-align: middle;" name="checkedAll" /></th>
            <th style="text-align: center;width:300px;">附件名称</th>
            <th style="text-align: center;width:260px;">文件类型</th>
            <th style="text-align: center;width:150px;">上传时间</th>
            <th style="text-align: center;width:100px;">上传人</th>
            <th style="text-align: center;width:150px;">操作</th>
        </tr>
    </thead>
    <tbody>
        @if (Model != null)
        {
            var MyCache = new MyCache.InProc.Cache();
            var UserID = Business.Platform.Users.CurrentUserID.ToString();
            
            
            var datalist =  Model.DataList as List<Pub_Annex>;

            var fileList1 = MyCache.Get(UserID) as List<WebMvc.Models.TemporaryFiles>;

            if (fileList1!=null)
            {
            foreach (WebMvc.Models.TemporaryFiles item in fileList1)
            {
            <tr>
                <th style="text-align: center; width: 60px;">
                    <input type="checkbox"  style="vertical-align: middle;display:none;" name="uploadFile" value="@item.FileID" onclick="InvertCheck(this.checked);"  /></th>
                <td style="text-align: center;width:240px;">@item.FileName.ToString().CutString(35)</td>
                @{
                Data.MSSQL.Dictionary dicDal = new Data.MSSQL.Dictionary();
                var dicProposalFileType = dicDal.GetByWhere(" Other='pxFile' and Value = '" + item.FileType + "'");
                if (dicProposalFileType != null)
                {
                    <td style="text-align: center;">@dicProposalFileType.Title</td>
                }
                else
                {
                    <td style="text-align: center;"></td>
                }
                }
                <td style="text-align: center;">@item.CreateTime.DateFormat("yyyy-MM-dd")</td>
                <td style="text-align: center;">@Business.Platform.Users.CurrentUserName</td>
                <td style="text-align: center;">                 
                    <input type="submit" style="display: none;" value="d" id="DeleteBut" name="DeleteBut" />
                    <a class="dellink" style="color:blue;" href="javascript:void(0);" onclick="DeleteModel('@item.FileID');return false;">删除</a>
                </td>
            </tr>
            }
            }

            foreach (var annex in datalist)
            {
            <tr>
                <th style="text-align: center; width: 60px;">
                    @if (annex.Invalid == 0)
                    {
                    <input type="checkbox"  style="vertical-align: middle;" name="checkFile" value="@annex.Annex_ID"  onclick="InvertCheck(this.checked);" />
                    }
                </th>
                <td style="text-align: center;width:240px;">@annex.AnnexName.ToString().CutString(35)</td>
                @{
                    Data.MSSQL.Dictionary dicDal = new Data.MSSQL.Dictionary();
                    var dicProposalFileType = dicDal.GetByWhere(" Other='pxFile' and Value = '" + annex.AnnexType + "'");
                    if (dicProposalFileType != null)
                    {
                    <td style="text-align: center;">@dicProposalFileType.Title</td>
                    }
                    else
                    {
                    <td style="text-align: center;"></td>
                    }
                }
                <td style="text-align: center;">@annex.CreateTime.ToString().DateFormat("yyyy-MM-dd")</td>
                @{
                                
                    var userid = annex.CreateBy.ToString();
                    var userName = new Business.Platform.Users().GetName(Guid.Parse(userid));
                }
                <td style="text-align: center;">@userName</td>
                <td style="text-align: center;" class="operateTD">
                    @{
                    if (annex.Invalid == 0)
                    {
                        <a class="viewlink" style="color:blue;" href="javascript:void(0);" onclick="DownFile('@annex.Annex_ID');">下载</a>
                        if (Model.Type == annex.MenuType.ToString() && annex.CreateBy.ToString() == Business.Platform.Users.CurrentUserID.ToString())
                        {
                        <span class="toolbarsplit"> </span> 
                        <a class="viewlink" style="color:blue;" href="javascript:void(0);" onclick="InvalidModel('@annex.Annex_ID');return false;">作废</a>
                        }
                    }
                    else
                    {
                        if (Model.Type == annex.MenuType.ToString() && annex.CreateBy.ToString() == Business.Platform.Users.CurrentUserID.ToString())
                        {
                         <a class="viewlink" style="color:red;text-decoration:none;" href="javascript:void(0);" onclick="CancleInvalidModel('@annex.Annex_ID');return false;">取消作废</a>
                        }
                        else
                        {
                    <a class="viewlink" style="color:red;text-decoration:none;" href="javascript:void(0);">已作废</a>
                        }
                    }
                    }
                </td>
            </tr>
            }
        }
    </tbody>
</table>
<script type="text/javascript">
    var dialog = top.mainDialog;
    var appid = '@ViewBag.AppID';
    var iframeid = '@ViewBag.Iframeid';
    var query = '@ViewBag.Query' + "&display=1";
    $(function () {

    });
    function ShowUploadFileView() {
        //弹框实现
        dialog.open({ id: "window_" + appid.replaceAll('-', ''), title: "上传文件", width: 600, height: 200, url: top.rootdir + '/Inf_Train/UploadFileView?' + query, openerid: iframeid });
    }
    function checkAll(checked) {
        $("input[name='checkFile']").prop("checked", checked);
    }

    function InvertCheck(checked) {
        if (!checked) {
            $("input[name='checkedAll']").prop("checked", false);
        }
    }
    //删除附件
    function DeleteModel(id) {
        //if ($(":checkbox[name='checkFile']:checked").size() == 0) {
        //    alert("您没有选择要删除的数据!"); return;
        //}
        //$(":checkbox[name='checkFile']").each(function () {
        //    if ($(this).attr("value") == id) {
        //        box = $(this);
        //    }
        //});
        if (!confirm('你确定要删除吗?')) {
            return false;
        }
        var box = null;
      
        if (box == null) {
            $(":checkbox[name='uploadFile']").each(function () {
                if ($(this).attr("value") == id) {
                    box = $(this);
                }
            });
        }
        $.ajax({
            url: "/Inf_Train/DFile?idString=" + id,
            type: "post",
            success: function (data) {

                if (data.success == true) {
                    box.parent().parent().remove();
                    alert("删除成功!");
                    // reloadiframe('tab_5826f65e540b41eb92c0939767734cef_iframe');

                }
                else {
                    alert("删除失败!")
                    return false;
                }
            },
            error: function (err) {
                alert("删除失败!")
                return false;
            }
        })
        //$.getScript("/Inf_Train/DeleteFile?idString=" + id, function () {
        //    if (json.message == null || json.message == "") {
        //        box.parent().parent().remove();
        //    }
        //});
    }

    function DownFile(id) {
        var url = "@Url.Action("DownLoadFile", "Inf_Train")" + "?idString=" + id;
        download_file(url);
    }
    /* ajax下载文件 url: 文件url路径*/
    function download_file(url) {
        if (typeof (download_file.iframe) == "undefined") {
            var iframe = document.createElement("iframe");
            download_file.iframe = iframe;
            document.body.appendChild(download_file.iframe);
        }
        download_file.iframe.src = url;
        download_file.iframe.style.display = "none";
    }

    //作废已入库的文件
    function InvalidModel(id) {
        if ($(":checkbox[name='checkFile']:checked").size() == 0) {
            alert("您没有选择要作废的数据!"); return;
        }
        if (!confirm('您真的要作废所选应用吗?')) {
            return false;
        }
        var box = null;
        $(":checkbox[name='checkFile']").each(function () {
            if ($(this).attr("value") == id) {
                box = $(this);
            }
        });
        $.getScript("/Inf_Train/InvalidFile?idString=" + id, function () {
            if (json.message == null || json.message == "") {
                window.location.reload();
            }
        });
    }
    //取消作废文件
    function CancleInvalidModel(id)
    {
        //if ($(":checkbox[name='checkFile']:checked").size() == 0) {
        //    alert("您没有选择要取消作废文件的数据!"); return;
        //}
        //if (!confirm('您真的要取消作废文件所选应用吗?')) {
        //    return false;
        //}
        var box = null;
        $(":checkbox[name='checkFile']").each(function () {
            if ($(this).attr("value") == id) {
                box = $(this);
            }
        });
        $.getScript("/Inf_Train/CancleInvalidFile?idString=" + id, function () {
            if (json.message == null || json.message == "") {
                window.location.reload();
            }
            else {
                alert("取消作废失败,请刷新后重新操作!");
            }
        });
    }

</script>

临时类
   /// <summary>
    /// 上传文档临时类
    /// </summary>
    public class TemporaryFiles
    {
        public int FileID { get; set; }
        public string FileName { get; set; }
        //public string FilePath { get; set; }
        public string FileType { get; set; }
        public DateTime CreateTime { get; set; }
        public string CreateBy { get; set; }
        public string SubMenuName { get; set; }
        public HttpPostedFileBase FileBase { get; set; }
        public string FilePath { get; set; }
        public string Instanceid { get; set; }
        public string BaseFileName { get; set; }
    }
    /// <summary>
    /// 附件临时集合
    /// </summary>
    public class AnnexList
    {
        public string Type { get; set; }
        public List<Pub_Annex> DataList { get; set; }
        public List<TemporaryFiles> FileList { get; set; }
    }
    /// <summary>
    /// 附件临时集合
    /// </summary>
    public class IT_IndustryTrackerAnnexList
    {
        public string Type { get; set; }
        public List<IT_IndustryTrackerAnnex> DataList { get; set; }
        public List<TemporaryFiles> FileList { get; set; }
    } //3 Controllers

    private static Pub_AnnexBLL annexBll = new Pub_AnnexBLL();        

static readonly string emailFrom = System.Configuration.ConfigurationManager.AppSettings["UserName"];

        private string UserID = Business.Platform.Users.CurrentUserID.ToString();

        MyCache.InProc.Cache MyCache = new MyCache.InProc.Cache();

 #region 添加附件文档
        /// <summary>
        /// 上传文件窗体
        /// </summary>
        public ActionResult UploadFileView()
        {
            return InsertAnnex();
        }

        /// <summary>
        /// 将文件存在临时集合中
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult InsertAnnex()
        {
            List<TemporaryFiles> FileList1 = new List<TemporaryFiles>();
            object objCache = MyCache.Get(UserID);
            if (objCache != null) FileList1 = MyCache.Get(UserID) as List<WebMvc.Models.TemporaryFiles>;

            GetPubParameter();
            var id = Request["instanceid"];
            var userID = Business.Platform.Users.CurrentUserID;
            if (Request.Files.Count != 0)
            {
                var folder = string.Format("{0}{1}{2}{3}\\", AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["InfTrainFiles"].Replace("~/", ""), id, "/" + DateTime.Now.ToString("yyyymmddhhmmssffff"));
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFileBase filebase = Request.Files[i];
                    if (filebase.ContentLength != 0)
                    {
                        string path = string.Empty;

                        var RandomName = filebase.FileName.Substring(filebase.FileName.LastIndexOf("\\") + 1);
                        path = folder + RandomName;
                        filebase.SaveAs(path);

                        TemporaryFiles uploadfile = new TemporaryFiles();
                        var fileFullName = filebase.FileName.Substring(filebase.FileName.LastIndexOf("\\") + 1);
                        uploadfile.FileName = fileFullName.Remove(fileFullName.LastIndexOf('.'));
                        uploadfile.FileID = FileList1.Count + 1;
                        uploadfile.FileType = Request["txtFileType"];
                        uploadfile.CreateTime = DateTime.Now;
                        uploadfile.CreateBy = userID.ToString();
                        uploadfile.FilePath = path;
                        uploadfile.Instanceid = id;
                        uploadfile.BaseFileName = filebase.FileName;

                        FileList1.Add(uploadfile);
                        MyCache.Insert(UserID, FileList1);

                        ViewBag.Script = "alert('添加成功!'); top.reloadchildiframe('uploadFile', 'tab_Add_iframe');new RoadUI.Window().close();";
                
                    }
                    else
                    {
                        ViewBag.Script = "alert('请选择文件或者文件大小为0KB的未上传成功!');";
                    }
                }
               
                
               // ViewBag.Script = "alert('添加成功!');new RoadUI.Window().reloadChild('/InventionPoint_Personal/InnovationPoint_InnovationPoint_AnnexView?instanceid=" + id + "&stepName=" + Request["stepName"] + "&" + "&type=InnovationPoint&" + ViewBag.Query + "','uploadFile');new RoadUI.Window().close();";
            }
            FileList1 = (from a in FileList1 orderby a.CreateTime descending select a).ToList<TemporaryFiles>();
            return View("~/Views/TrainingInsight/Inf_Train/InfTrain_InfTrain_Upload.cshtml");
        }
        
        #endregion      

        #region 文档列表展示
        /// <summary>
        /// 文件列表展示页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AnnexView()
        {
            var id = Request["instanceid"];
            string strWhere = string.Empty;
            var IFTemp = new List<Pub_Annex>();
            object objIF = MyCache.Get(UserID + "PX");
            if (objIF != null)
                IFTemp = objIF as List<Pub_Annex>;

            var annex = new DataTable();

            if (id != "" && id != string.Empty)
            {
                strWhere = " Particular_ID = '" + id + "' and MenuType = 'InfTrain'";
                annex = annexBll.GetList(strWhere, " createtime desc ");
            }
            GetPubParameter();
            var modelList = new List<Pub_Annex>();
            if (annex.Rows.Count > 0)
            {
                foreach (DataRow row in annex.Rows)
                {
                    var model = annexBll.DataRowToModel(row);
                    if (IFTemp.Count > 0)
                    {
                        var file = IFTemp.SingleOrDefault(i => i.Annex_ID == model.Annex_ID);
                        if (file != null)
                        {
                            modelList.Add(file);
                        }
                        else
                        {
                            modelList.Add(model);
                        }
                    }
                    else
                    {
                        modelList.Add(model);
                    }
                }
            }

            ViewBag.InstanceID = id;
            MyCache.Remove(UserID + "PX");
            MyCache.Insert(UserID + "PX", IFTemp);          
            return View("~/Views/TrainingInsight/Inf_Train/Annex_Edit.cshtml", new AnnexList { Type = "InfTrain", DataList = modelList});
        }

        /// <summary>
        /// 文件详情页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AnnexDetail()
        {
            var id = Request["instanceid"];
            string strWhere = string.Empty;
            var annex = new DataTable();

            if (id != "")
            {
                strWhere = " Particular_ID = '" + id + "' and MenuType = 'InfTrain'";
                annex = annexBll.GetList(strWhere, " createtime desc ");
            }
            GetPubParameter();
            var modelList = new List<Pub_Annex>();
            if (annex.Rows.Count > 0)
            {
                foreach (DataRow row in annex.Rows)
                {
                    var model = annexBll.DataRowToModel(row);
                    modelList.Add(model);
                }
            }
            return View("~/Views/TrainingInsight/Inf_Train/Annex_Detail.cshtml", new AnnexList { DataList = modelList });
        }
        #endregion

        #region 附件到数据库
        /// <summary>
        /// 添加附件到数据库   
        /// </summary>       
        public string Annex_Update(string modelid)
        {
            var result = "";
            var folder = string.Format("{0}{1}{2}\\", AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["InfTrainFiles"].Replace("~/", ""), modelid);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            object objUpdate = MyCache.Get(UserID + "PX");
            if (objUpdate != null)
            {
                List<Pub_Annex> InvalidUpdate = new List<Pub_Annex>();
                InvalidUpdate = objUpdate as List<Pub_Annex>;
                foreach (var item in InvalidUpdate)
                {
                    annexBll.Update(item);
                }
                MyCache.Remove(UserID + "PX");

            }
            //读取缓存中的数据
            object obj = MyCache.Get(UserID);
            List<TemporaryFiles> FileList1 = new List<TemporaryFiles>();
            if (obj != null) FileList1 = obj as List<WebMvc.Models.TemporaryFiles>;
            else return result;
            if (FileList1.Count > 0)
            {
                foreach (var item in FileList1)
                {
                    Pub_Annex annex = new Pub_Annex();
                    annex.Annex_ID = Guid.NewGuid().ToString();
                    annex.AnnexName = item.FileName;

                    var uploadfile = item.BaseFileName;
                    string temp = item.FilePath;
                    temp = temp.Replace(AppDomain.CurrentDomain.BaseDirectory, "");
                    temp = string.Format("{0}{1}", "~/", temp);
                    annex.AnnexPath = temp; //string.Format("{0}{1}/{2}", ConfigurationManager.AppSettings["ProposalFiles"], modelid, uploadfile); 
                    annex.AnnexType = item.FileType;
                    annex.CreateBy = item.CreateBy;
                    annex.CreateTime = item.CreateTime;
                    annex.MenuType = "InfTrain";
                    annex.Particular_ID = modelid;
                    annexBll.Add(annex);
                }
                MyCache.Remove(UserID);
                
            }
            return result;
        }
        #endregion

        #region  文件删除下载


        /// <summary>
        /// 删除上传的文件InfTrainFiles
        /// </summary>
        public JsonResult DFile()
        {
            JsonResult json = new JsonResult();
            string idString = Request["idString"].ToString();
            List<TemporaryFiles> FileList = new List<TemporaryFiles>();
            object objCache = MyCache.Get(UserID);
            if (objCache != null) FileList = MyCache.Get(UserID) as List<WebMvc.Models.TemporaryFiles>;
            if (!string.IsNullOrEmpty(idString))
            {
                if (FileList != null)
                {
                    var idList = idString.Split(',');
                    foreach (var id in idList)
                    {
                        if (!string.IsNullOrEmpty(id))
                        {
                            var fileID = 0;
                            if (int.TryParse(id, out fileID) && fileID != 0)
                            {

                                var item = FileList.SingleOrDefault(i => i.FileID == int.Parse(id.ToString()));

                                var folder = string.Format("{0}{1}{2}\\", AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["InfTrainFiles"].Replace("~/", ""), id);
                                if (System.IO.File.Exists(item.FilePath))
                                {
                                    System.IO.File.Delete(item.FilePath);
                                }
                                FileList.Remove(item);
                                MyCache.Insert(UserID, FileList);
                                //Response.Write("var json = {\"success\":1,\"message\":\"\"}");
                                json.Data = new { success = true };
                            }
                            else
                            {
                                json.Data = new { success = false };
                            }
                        }
                    }
                }
            }
            else
            {
                json.Data = new { success = false };
            }
            return json;
        }
        /// <summary>
        /// 删除上传的文件InfTrainFiles
        /// </summary>
        public void DeleteFile()
        {
            string idString = Request["idString"].ToString();
            List<TemporaryFiles> FileList = new List<TemporaryFiles>();
            object objCache = MyCache.Get(UserID);
            if (objCache != null) FileList = MyCache.Get(UserID) as List<WebMvc.Models.TemporaryFiles>;
            if (!string.IsNullOrEmpty(idString))
            {
                if (FileList != null)
                {
                    var idList = idString.Split(',');
                    foreach (var id in idList)
                    {
                        if (!string.IsNullOrEmpty(id))
                        {
                            var fileID = 0;
                            if (int.TryParse(id, out fileID) && fileID != 0)
                            {

                                var item = FileList.SingleOrDefault(i => i.FileID == int.Parse(id.ToString()));

                                var folder = string.Format("{0}{1}{2}\\", AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["InfTrainFiles"].Replace("~/", ""), id);
                                if (System.IO.File.Exists(item.FilePath))
                                {
                                    System.IO.File.Delete(item.FilePath);
                                }
                                FileList.Remove(item);
                                MyCache.Insert(UserID, FileList);
                                Response.Write("var json = {\"success\":1,\"message\":\"\"}");
                            }
                            else
                            {
                                Response.Write("var json = {\"success\":1,\"message\":要删除的文件不存在!\"\"}");
                            }
                        }
                    }
                }
            }
            else
            {
                Response.Write("var json = {\"success\":1,\"message\":请选择要删除的文件!\"\"}");
            }
        }
        /// <summary>
        /// 文档打包下载
        /// </summary>
        public void DownLoadFile()
        {
            var idStr = Request["idString"];
            if (!string.IsNullOrEmpty(idStr))
            {
                var idList = idStr.Split(',');
                List<string> listFilePath = new List<string>();
                foreach (var id in idList)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        //调用得到一个对象实体方法 
                        var annex = annexBll.DataRowToModel(annexBll.GetModel(" Annex_ID = '" + id + "' ").Rows[0]);
                        if (annex.Invalid == 1)
                        {
                            Response.Write("<script>alert('文件作废失败不能下载!');</script>");
                        }
                        else
                        {
                            string filePath = Server.MapPath(annex.AnnexPath);//获取下载的路径
                            FileInfo fileInfo = new FileInfo(filePath);
                            listFilePath.Add(annex.AnnexPath);
                        }
                    }
                }
                //压缩文件名字
                string zipname = DateTime.Now.ToString().ToString().Replace(" ", "").Replace(":", "").Replace("/", "");
                ZipDownLoad.ZipFileDownLoad(listFilePath, zipname);
            }
        }


        /// <summary>
        /// 文档打包下载
        /// </summary>
        public void DLFile()
        {
            var idStr = Request["idString"];
            if (!string.IsNullOrEmpty(idStr))
            {
                var idList = idStr.Split(',');
                List<string> listFilePath = new List<string>();
                foreach (var id in idList)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        //调用得到一个对象实体方法 
                        //var annex = annexBll.DataRowToModel(annexBll.GetModel(" Particular_ID = '" + id + "' ").Rows[0]);
                        var annex = annexBll.GetModel(" Particular_ID = '" + id + "' ");
                        if (annex.Rows.Count > 0)
                        {
                             for (int i = 0; i < annex.Rows.Count; i++)
                              {
                                if (annex.Rows[i]["Invalid"].ToString() == "1")
                                {
                                    Response.Write("<script>alert('文件作废失败不能下载!');</script>");
                                }
                                else
                                {
                                    string filePath = Server.MapPath(annex.Rows[i]["AnnexPath"].ToString());//获取下载的路径
                                    FileInfo fileInfo = new FileInfo(filePath);
                                    listFilePath.Add(annex.Rows[i]["AnnexPath"].ToString());
                                }
                             }
                        }
                        else
                        {
                            Response.Write("<script>alert('对不起文件不存在!');</script>");
                        }
                       
                    }
                }
                //压缩文件名字
                string zipname = DateTime.Now.ToString().ToString().Replace(" ", "").Replace(":", "").Replace("/", "");
                ZipDownLoad.ZipFileDownLoad(listFilePath, zipname);
            }
        }
        #endregion

        #region 文件 作废 取消
        /// <summary>
        /// 文件作废
        /// </summary>
        public void InvalidFile()
        {
            string idString = Request["idString"].ToString();
            List<Pub_Annex> InvalidTemp = new List<Pub_Annex>();
            object ObjIF = MyCache.Get(UserID + "PX");
            if (ObjIF != null) InvalidTemp = ObjIF as List<Pub_Annex>;
            if (!string.IsNullOrEmpty(idString))
            {
                var idList = idString.Split(',');
                foreach (var id in idList)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        var model = annexBll.GetModel(" Annex_ID ='" + id + "'");
                        if (model.Rows.Count > 0)
                        {
                            var annex = annexBll.DataRowToModel(model.Rows[0]);
                            annex.Invalid = 1;
                            //annexBll.Update(annex);
                            InvalidTemp.Add(annex);

                            Response.Write("var json = {\"success\":1,\"message\":\"\"}");
                        }
                        else
                        {
                            Response.Write("var json = {\"success\":1,\"message\":文件作废失败,请检查文件是否存在!\"\"}");
                        }
                    }
                }
                MyCache.Remove(UserID + "PX");
                MyCache.Insert(UserID + "PX", InvalidTemp);
            }
        }

        /// <summary>
        /// 取消作废文件
        /// </summary>
        public void CancleInvalidFile()
        {
            string idString = Request["idString"].ToString();
            List<Pub_Annex> InvalidTemp = new List<Pub_Annex>();
            object ObjIF = MyCache.Get(UserID + "PX");
            if (ObjIF != null) InvalidTemp = ObjIF as List<Pub_Annex>;
            if (!string.IsNullOrEmpty(idString))
            {
                var idList = idString.Split(',');
                foreach (var id in idList)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        var model = InvalidTemp.SingleOrDefault(i => i.Annex_ID == id);
                        if (model != null)
                        {
                            InvalidTemp.Remove(model);
                            Response.Write("var json = {\"success\":1,\"message\":\"\"}");
                        }
                        else
                        {
                            var annex = annexBll.GetModel(" Annex_ID ='" + id + "'");
                            if (annex.Rows.Count > 0)
                            {
                                var annexmodel = annexBll.DataRowToModel(annex.Rows[0]);
                                annexmodel.Invalid = 0;
                                InvalidTemp.Add(annexmodel);
                                //将作废文件实体放入到缓存中

                                Response.Write("var json = {\"success\":1,\"message\":\"\"}");
                            }
                        }
                    }
                }
                MyCache.Remove(UserID + "PX");
                MyCache.Insert(UserID + "PX", InvalidTemp);
            }
        }
        #endregion        

 

posted on 2015-06-15 12:32  zmmlczy  阅读(217)  评论(0编辑  收藏  举报

导航