直接上代码:
前端【表单与ajax】:
<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语言测试的):