ajax图片上传

2022-11-29 16:06:29 浏览数 (1)

直接上代码:

前端【表单与ajax】:

代码语言:javascript复制
  <div>
        <input type="file" class="form-control" id="filePic"  onchange="uploadImg()"/>
    </div>
    <div>
        <img src="" alt="" id="picShow" width="100" height="100" />
    </div>  
  <script>
//图片上传
    function uploadImg() {
        var formData = new FormData();
        formData.append("filePic", $("#filePic").get(0).files[0]);
        $.ajax({
            url: "/Home/UploadPic",
            type: 'POST',
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉equerry不要去设置Content-Type请求头
            contentType: false,
            beforeSend: function () {//发送之前
                console.log("正在进行,请稍候");
            },
            success: function (data) {
                if (data != "") {
                    $("#picShow").attr("src", data);//图片路径
                } else {
                    console.log("上传失败");
                }
            },
            error: function (responseStr) {
                console.log("error");
            }
        });
    }
    </script>

后台代码(这里是.NET语言测试的):

代码语言:javascript复制
   public ActionResult UploadPic(HttpPostedFileBase filePic)
        {
            if (filePic != null)
            {
                var path = "/uploads/"   filePic.FileName;
                filePic.SaveAs(Server.MapPath(path));
                return Content(path);
            }
            else
            {
                return Content("");
            }
        }

0 人点赞