• C# mvc 上传多个附件


    1  <div class="col-xs-12 mcp-list-item" style="margin-top:20px">
    2                                     <div class="mcp-list-item-title">附件</div>
    3                                     <input onchange="upload()" id="uploadFile" name="uploadFile" placeholder="多个请按下Ctrl后选取文件" type="file" value="文件选取" multiple="multiple">
    4                                 </div>
    5                                 <div class="col-xs-12 mcp-list-item">
    6                                     <a class="btn btn-success" onclick="btn_upload()"><i class="fa fa-upload"></i>开始上传</a>
    7                                 </div>



    //下面这一段代码是用来显示图片容器的

      <div id="imgList">
              <img id="fileUrl" style=" 100px; height: 100px; border-radius: 100px;" />
          </div>
          
          <div id="fileList">
    
          </div>
     
            //图片上传
            function upload() {
    
                var f1 = document.getElementById('uploadFile').files;
                if (f1.length>0) {
                    var form = $('#imgList');
                    for (var i = 0; i < f1.length; i++) {
    
                        var src1 = window.URL.createObjectURL(f1[i]);
                        var imgid='fileUrl_'+i;
                        var oldElement = $('#fileUrl');
                        var newElement = $(oldElement).clone();
                        $(oldElement).attr('id', imgid);
                        $(oldElement).before(newElement);
                        $(oldElement).appendTo(form);
                        $(oldElement).attr('src', src1);
                       // $('#' + imgid).src = src1
                    }
                }
                
               
    
    
    
                //var f = document.getElementById('uploadFile').files[0];
             
                //var src = window.URL.createObjectURL(f);
                //var filetype = "GIF,JPEG,JPG,PNG,pdf";
                //document.getElementById('fileUrl').src = src;
    
                
    
                //if (f == null || f == "") {
                //    dialogMsg('请选择文件!', 0);
                //    return;
                //} else if (f != "" && f != undefined && f != null) {
                //    var imgtype = ff.toLowerCase().split('.');
                //    if (filetype.indexOf(imgtype[1].toUpperCase()) == -1) {
                //        dialogMsg('图片类型必须是.gif,jpeg,jpg,png,pdf中的一种!', 0);
                //        return;
                //    }
                //}
            
    
            }
            function btn_upload() {
        
                var refids = [];
                var rows = $('#Delivery_Grid').datagrid('getRows');
                $.each(rows, function (index, item) {
                    refids.push(item.reforderid);
                   
                });
    
                var numArr = [];
                var txt = $("#fileList").find("input:file"); //获取所有上传附件框
                for (var i = 0; i < txt.length; i++) {
                    numArr.push(txt.eq(i).attr('id'));       //将附件框的ID添加到数组中
                }
    
    
                if (!$('#formState').Validform()) {
                    return false;
                }
                var postData = $("#formState").GetWebControls();
    
                $.ajaxFileUpload({
                    url: "/TMS.Service/ServiceMilestone/UploadFile?reforderid=" + refids.join(','),
                    secureuri: false,
                    fileElementId: 'uploadFile',
                    dataType: 'json',
                    //data: postData,
                    success: function (data) {
                        if (data.status) {
                            dialogMsg(data.message, 1);
                      
                            document.getElementById('fileUrl').src = "";
                            document.getElementById('uploadFile').src = "";
    
                        } else {
                            dialogMsg(data.msg, 0);
                        }
                    }
                });
    
            }

    记得引入   <script src="~/Content/scripts/uploadify/ajaxfileupload.js"></script>

    后台代码:

      [HttpPost]
            public ActionResult UploadFile(MilestoneInfo minfo)
            {
    
                try
                {
    
                    var filelist = new List<Cargo.Entity.FileInfoEntity>();
                    if (minfo == null)
                    {
                        throw new Exception("找不到milestone节点所属的业务信息 ");
                    }
    
                    if (Request != null && Request.Files != null && Request.Files.Count > 0)
                    {
                        string FileServerUrl = ConfigurationManager.AppSettings["FileServerUrl"].ToString();
                        string serverBasePath = AppDomain.CurrentDomain.BaseDirectory + @"Upload	emp";
                        DirectoryInfo dir = new DirectoryInfo(serverBasePath);
                        if (!dir.Exists)
                        {
                            dir.Create();
                        }
                        foreach (string fileStr in Request.Files)
                        {
                            HttpPostedFileBase file = Request.Files[fileStr] as HttpPostedFileBase;
                            if (file != null && file.ContentLength > 0)
                            {
                                string filename = Path.GetFileName(file.FileName);
                                string savePath = serverBasePath + @"" + filename;
                                var fileExtName = Path.GetExtension(savePath);
                                file.SaveAs(savePath);
                                string uploadDate = DateTime.Now.ToString("yyyyMMdd");
                                string address = FileServerUrl + $"Home/UploadFile?module={TMS_Enum.TMS_SysFileInfoEnum.TMS_module.ToString()}&folderId={TMS_Enum.TMS_SysFileInfoEnum.TMS_folderId.ToString()}&uploadDate=" + uploadDate;
                                var buffer = new WebClient().UploadFile(address, "post", savePath);
                                string result = Encoding.UTF8.GetString(buffer);
    
                                var serverFilePath = FileServerUrl + result.Replace("~/", ""); //最终服务器存储的地址
                                                                                               //判断文件是不是存在 清空临时存储的文件
                                if (System.IO.File.Exists(savePath))
                                {
                                    //如果存在则删除
                                    System.IO.File.Delete(savePath);
                                }
                                filelist.Add(new Cargo.Entity.FileInfoEntity
                                {
                                    FileExtensions = fileExtName,
                                    FilePath = serverFilePath,
                                    FileName = filename,
    
                                });
                            }
                        }
     
                    }
    
    
                    //这里为了避免上传文件事务长时间锁死,所以放置到这里进行操作,先上传耗时的文件操作,再考虑操作数据库
                    SaveMilestone(
                        minfo,
                        filelist);
                    return new ResponseModel { status = true, msg = "提交成功!" };
    
                }
                catch (Exception ex)
                {
    
                    return new ResponseModel { status = false, msg = ex.Message };
                }
    
            }


  • 相关阅读:
    Qt Quick 简单介绍
    Windows下ElasticSearch及相关插件的安装
    Light OJ 1317 Throwing Balls into the Baskets 概率DP
    Cocos2d-x-lua学习点滴
    JAVA网络编程--UDP通信
    ASP.NET Web API 应用教程(一) ——数据流使用
    NGUI创建Camera参数为Simple 2D的UI UI对象的结构UI Root(2D)
    端口扫描器——ZenmapKail Linux渗透测
    直接操作游戏对象C#游戏开发
    BeagleBone Black项目实训手册(大学霸内部资料)
  • 原文地址:https://www.cnblogs.com/benbenfishfish/p/10407495.html
Copyright © 2020-2023  润新知