C# 文件上传

获取POST 请求发送的文件 并保存到服务器

 HttpPostedFile file = System.Web.HttpContext.Current.Request.Files["file"];
            //获取上载文件名称
            string _FileName = file.FileName;
            //后缀
            string _Ext = _FileName.Substring(_FileName.LastIndexOf("."));
            //新文件名
            string _NewName = "class-" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            //获取上传路径
            string _ImgPath = System.Configuration.ConfigurationManager.AppSettings["Field_img"].ToString();
             //存储文件的路径及文件
            string _Path = Server.MapPath(_ImgPath) + _NewName + _Ext;
            //存文件到服务器磁盘
            file.SaveAs(_Path);

批量上传图片 后端+js前端

这里的前端样式可以去我的资源那里下载

后端代码

try
            {
                //获取url中的参数
                var PId = Request.QueryString["PId"];
                //截取字节流数据
                HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                if (files.Count > 0)
                {
                    for (var i = 0; i < files.Count; i++)
                    {
                        //获取字节流数据
                        var file = Request.Files["myFile[" + i + "]"];
                        //重命名文件
                        var fileName = file.FileName;
                        //获取文件后缀名
                        var fileExt = Path.GetExtension(fileName);
                        //获取年月日时分秒
                        var date = DateTime.Now.ToString("yyyyMMddHHmmss");
                        //生成三位数的随机数
                        var random = new Random();
                        var randomNum = random.Next(100, 999);
                        //生成新的文件名= 当前Id+年月日时分秒+随机数+后缀名
                        var newFileName = PId + "-" + date + randomNum + fileExt;
                        //将文件保存到服务器上
                        //先判断路径是否存在
                        var day = DateTime.Now.ToString("yyyyMMdd");
                        var path = Server.MapPath("~/Upload/" + day);
                        if (!Directory.Exists(path))
                        {
                            //没有文件路径则创建
                            Directory.CreateDirectory(path);
                        }
                        var filePath = Server.MapPath("~/Upload/" + day + "/");
                        //保存到服务器
                        file.SaveAs(filePath + newFileName);
                        //将文件信息保存到数据库
                        /*这里写保存图片路径到数据库的业务*/
                    }
                    return Json(new { data = 200 });
                }
                else
                {
                    return Success(-1, "请选择需要上传的图片");
                }
            }
            catch (Exception ex)
            {
                return Success(-1, ex.Message);
            }

前端(js语法)

html

<div class="form-group">
                        <label class="control-label col-md-2">上传图片:</label>
                        <div class="col-md-8">
                            <div class="main">
                                <div class="upload-content">
                                    @*<h3>上传图片</h3>*@
                                    <div class="content-img">
                                        <ul class="content-img-list"></ul>
                                        <div class="file">
                                            <i class="gcl gcladd"></i>
                                            <input type="file" name="file" accept="image/*" id="upload" multiple>
                                        </div>
                                    </div>
                                    <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
                                        <div class="modal-dialog modal-lg" role="document">
                                            <div class="modal-content">

                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">

                            <button type="button" class="btn btn-info" id="btn-submit-upload"><span class="glyphicon glyphicon-ok"></span>保存</button>
                        </div>
                    </div>

js

<script>
        var imgFile = []; //文件流
        var imgSrc = []; //图片路径
        var imgName = []; //图片名字
        var imgId = [];//后端返回的图片主键

        let imageList = @Html.Raw(Json.Encode(@ViewBag.Image));
        if (imageList.length > 0) {
            console.info(imageList)

            for (var item = 0; item < imageList.length; item++) {
                imgSrc.push(imageList[item].PictureUrl);
                imgId.push(imageList[item].Id);
                //下面两个字段随便存啥,只有与后端返回的数组长度一致即可,用于占位方便前端的假删除
                imgFile.push(imageList[item].Id);
                imgName.push(imageList[item].Id);
            }
            var imgBox = '.content-img-list';
            addNewContent(imgBox);
            console.log("=====赋值后", imgSrc)
            console.log("=====赋值后图片id", imgId)
        } else {//只有当后台存在数据才显示打印
            var div = document.getElementById("printPic");
            div.setAttribute("style", "display:none");
        }

        $(function () {
            // 鼠标经过显示删除按钮
            $('.content-img-list').on('mouseover', '.content-img-list-item', function () {
                $(this).children('div').removeClass('hide');
            });
            // 鼠标离开隐藏删除按钮
            $('.content-img-list').on('mouseleave', '.content-img-list-item', function () {
                $(this).children('div').addClass('hide');
            });
            // 单个图片删除
            $(".content-img-list").on("click", '.content-img-list-item a .gcllajitong', function () {
                var index = $(this).parent().parent().parent().index();
                console.log("触发删除==》", index)
                if (imgId.length > 0) {//证明存在后端图片
                    console.log("存在需要删除的后端图片")
                    if (imgId[index]) {
                        console.log("执行删除后端")
                        removeImg(imgId[index], index)
                    }
                }
                console.log("执行删除前端")
                imgSrc.splice(index, 1);
                imgFile.splice(index, 1);
                imgName.splice(index, 1);
                var boxId = ".content-img-list";
                addNewContent(boxId);
            });


            $(".content-img-list").on("click", '.content-img-list-item a .gclfangda', function () {
                var index = $(this).parent().parent().parent().index();
                $(".modal-content").html("");

                var bigimg = $(".modal-content").html();
                $(".modal-content").html(bigimg + '
+ imgSrc[index] + '" alt="" style="width:96%;height:100%"><div>'); }); }); //图片上传 $('#upload').on('change', function (e) { var imgSize = this.files[0].size; if (imgSize > 1024 * 1024 * 1) { //1024kb*1024K=1M return alert("上传图片不能超过1M"); }; if (this.files[0].type != 'image/png' && this.files[0].type != 'image/jpeg' && this.files[0].type != 'image/gif') { return alert("图片上传格式不正确"); } var imgBox = '.content-img-list'; var fileList = this.files; for (var i = 0; i < fileList.length; i++) { var imgSrcI = getObjectURL(fileList[i]); imgName.push(fileList[i].name); imgSrc.push(imgSrcI); imgFile.push(fileList[i]); } addNewContent(imgBox); this.value = null; //上传相同图片 }); //提交请求 $('#btn-submit-upload').on('click', function () { // FormData上传图片 var formFile = new FormData(); // 遍历图片imgFile添加到formFile里面 $.each(imgFile, function (i, file) { formFile.append('myFile['+i+']', file); }); $.ajax({ url: '/T_TaskMian/AddFile?Pid='+@ViewBag.PId, type: 'POST', data: formFile, async: true, cache: false, contentType: false, processData: false, dataType: 'json', success: function (res) { console.log(res); if (res.data == 200) { alert("保存成功") location.reload(); //$("#adviceContent").val(""); // $("#contact").val(""); } else { alert(res.msg); location.reload(); //$('.content-img .file').show(); //$("#adviceContent").val(""); //$("#cotentLength").text("0/240"); //$("#contact").val(""); //imgSrc = []; imgFile = []; imgName = []; //addNewContent(".content-img-list"); } } }) }); //删除后端 function removeImg(obj, index) { $.ajax({ url: '/T_TaskMian/DeleteFile?Id='+obj, type: 'GET', async: true, cache: false, contentType: false, processData: false, success: function (res) { console.log(res); if (res.data == 200) { alert("成功删除!") location.reload(); } else { alert(res.msg); location.reload(); } } }); } //图片展示 function addNewContent(obj) { // console.log(imgSrc) $(obj).html(""); for (var a = 0; a < imgSrc.length; a++) { var oldBox = $(obj).html(); $(obj).html(oldBox + '<li class="content-img-list-item"><img src="' + imgSrc[a] + '" alt="">' + '

你可能感兴趣的:(C#开发,asp.net)