Js上传文件

简介

作为一个刚刚入门的小白,在这里整理一些自己写过的代码,大多数的代码出处都找不到,如果有用过你们代码,请联系我QQ:1206062480;我会表明出处。

js实现文件上传

/*html部分*/
<div class="panel-heading">
                <h3>人员信息</h3>
                <form id="frmsearch" class="form-inline">
                    <div class="form-group">
                    <input id="img" type="file" class="form-control width-sm" style="display: none">
                    &nbsp;&nbsp;
                    <button type="button" class="btn btn-primary" style="float: right;" onclick="addImg()">
                        上传
                    </button>
                </form>
            </div>
<div class="modal fade" id="imgModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="userModalLabel">
                        电子签名
                    </h4>
                </div>
                <div class="modal-body" style="text-align: center">
                    <form id="formImg">
                        <div class="form-group">
                            <img id="image" src="" style="width:50%;height:50%;margin:auto" />
                            <div id="imageError" style="color:red; font-size:14px">
                            </div>
                        </div>                       
                    </form>
                </div>
            </div>
        </div>
    </div>
function addImg(id) {
            if (id) {
                $("#img").click();
                $("#img").change(function (e) {
                    var fileName = e.target.files[0];//js 获取文件对象
                    if (fileName !== undefined) {
                        var file_typename = fileName.name.substring(fileName.name.lastIndexOf('.'));
                        //判断图片格式,若上传excel即同理
                        if (file_typename === '.jpeg' || file_typename === '.png' || file_typename === '.jpg') {
                            $("#filename").css("display", "block");
                            $("#filename").val(fileName.name);
                            UpladFile(fileName, id);
                        } else {
                            toastr.error("请选择正确的文件类型!")
                        }
                    } else {
                        toastr.error("请选择正确的文件!")
                    }
                });
            }
        }

        function UpladFile(fileObj, id) {
            var form = new FormData(); // FormData 对象
            form.append("file", fileObj); // 文件对象
            form.append("userId", id);
            $.ajax({
                url: '/Worker/ImportImg',                      //url地址
                type: 'post',                 //上传方式
                data: form,                   // 上传formdata封装的数据
                dataType: 'json',
                cache: false,                  // 不缓存
                processData: false,        // jQuery不要去处理发送的数据
                contentType: false,         // jQuery不要去设置Content-Type请求头
                success: function (data) {           //成功回调
                    if (data.succeed == true) {
                        succeedTip("上传成功!");
                    } else {                         //失败回调
                        errorTip(data.error);
                    }
                }
                //,
                //error: function (data) {           //失败回调
                //    toastr.error(data.error, "导入失败!");
                //}
            });
        }

        function errorTip(msg, norefresh) {
            toastr.error(msg, "上传失败!");
            if (!norefresh) {
                setTimeout(function () {
                    window.location.reload();
                }, 1500)
            }
        }

        function getImg(id) {
            $('#imgModal').modal('show');
            if (id) {
                $.ajax({
                    url: "/Worker/GetUserById",
                    type: 'post',
                    data: { id: id },
                    dataType: 'json',
                    success: function (data) {
                        if (data.succeed === true) {
                            var dataJson = data.result;
                            var img = dataJson.ImagePath;
                            if (!img) {
                                $("#imageError").css("display", "block");
                                $("#imageError").html("当前用户暂无电子签名!");                              
                            } else {
                                var str = img.split('\\');
                                var path = "../" + str[str.length - 2] + "/" + str[str.length - 1];
                                $("#image").attr('src', path);
                            }
                        } else {
                            toastr.error("数据获取失败!");
                        }
                    }
                })
            }
        }
//后台处理
public ActionResult ImportImg(HttpPostedFileBase file)
        {
            try
            {
                var db = new Context();
                var fileName = file.FileName;
                var id = Request["userId"];
                var filePath = Server.MapPath(string.Format("~/{0}", "ImageFile"));
                file.SaveAs(Path.Combine(filePath, fileName));
                var user = db.User.SingleOrDefault(x => x.ID.ToString() == id);
                if (user == null)
                {
                    return Json2(new JsonOkay("上传失败,用户不存在!"));
                }
                else
                {
                    var path = Path.Combine(filePath, fileName);
                    if (path.IsNullOrEmpty())
                        return Json2(new JsonOkay("上传的签名为空!"));
                    user.ImagePath = path;
                    db.SaveChanges();
                    return Json2(new JsonOkay());

                }
            }
            catch (Exception e)
            {
                return Json2(new JsonOkay(e.Message));
            }
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值