.netcore之文件上传

.netcore 取消了之前.netframework的HttpPostedFileBase 。          

整理了一个上传文件的流程,可以选择跳转或不跳转页面。

  #引入jQuery以及 jQuery的jQuery.form.js,一定要先引入jQuery

<script src="../../../content/js/jquery.3.0.1.js"></script>

<script src="../../../content/js/jquery.form.js"></script>

<script>

               function RuturnLoginResult() {

                                $('#UserLoginFrom').ajaxSubmit(function (data) {

                                    alert(data);
                                })

                                return false;//这里必须要返回false,不然依然会跳转。

                            }

</script>

<body>

        <form class="form-horizontal" method="post" enctype="multipart/form-data" action="/SysManager/FileSave" onsubmit="return RuturnLoginResult();" id="UserLoginFrom">
                                <div>
                                    <div>
                                        <div class="col-md-6 input-group">
                                            <span class="input-group-addon">选择恢复文件</span>

                                            <input class="col-md-6" type="file" name="files" multiple />                                            <span class="input-group-btn">
                                                <button type="button" class="btn btn-info btn-search" onclick="dump()">...</button>
                                            </span>
                                        </div>
                                        
                                        <input class="col-md-3 btn btn-info btn-search" type="submit" value="恢复备份" />
                                    </div>
                                </div>
                            </form>

</body>

后台controller方法

 public async Task<IActionResult> FileSave(List<IFormFile> files)
        {
           // fil = files;
            var file = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            string webRootPath = hostingEnvironment.WebRootPath;
            string contentRootPath = hostingEnvironment.ContentRootPath;
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    string fileExt = "doc";
                    /// string fileExt = GetFileExt(formFile.FileName); //文件扩展名,不含“.”
                    long fileSize = formFile.Length; //获得文件大小,以字节为单位
                    string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //随机生成新的文件名
                    var filePath = webRootPath + "/upload/" + formFile.FileName;
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {

                        await formFile.CopyToAsync(stream);
                    }
                }
            }
           
            return Json(filePath );
        }

猜你喜欢

转载自blog.csdn.net/mingminglv1/article/details/81171811
今日推荐