AJAX 上传图片到磁盘并通过restful保存图片路径到数据库 添加客户操作
1.form表单,包括其他字段
<form class="form-horizontal" enctype="multipart/form-data" > <div class="card-body" > <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">客户名称</label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" id="name" placeholder="请输入名称"> </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">客户地址</label> <div class="col-sm-10"> <input type="text" class="form-control" name="address" id="address" placeholder="请输入地址"> </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">手机</label> <div class="col-sm-10"> <input type="text" class="form-control" name="phone" id="phone" placeholder="请输入手机号"> </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">QQ</label> <div class="col-sm-10"> <input type="text" class="form-control" name="qq" id="qq" placeholder="请输入qq"> </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">客户等级</label> <div class="col-sm-10"> <select name="level" id="level" class="form-control"> <option value="选择级别" label="选择级别">---</option> <option value="普通客户">普通客户</option> <option value="vip客户">vip客户</option> <option value="超级vip客户">超级vip客户</option> <option value="钻石vip客户">钻石vip客户</option> </select> </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">收款账号</label> <div class="col-sm-10"> <input type="text" class="form-control" name="accounts" id="accounts" placeholder="请输入 收款账号"> </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">收款码</label> <div class="col-sm-10"> <input type="file" name="file" id="photoFile">//photoFile绑定函数内的代码获取二进制数据 </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label"></label> <div class="col-sm-10"> <input type="button" id="submit" class="form-control" value="提交"> </div> </div> </div> <!-- /.card-footer --> </form>
2.JS代码
//ID为submit的按钮绑定单击事件执行保存函数 $("#submit").click(function(){ //alert(888); upload();//调用上传图片方法 //创建客户对象 $customer={"name": $("#name").val(), "address": $("#address").val(), "phone": $("#phone").val(), "qq": $("#qq").val(), "level": $("#level").val(), "accounts": $("#accounts").val() }; //alert($("#name").val()) //传递对象到后台保存的AJAX $.ajax({ cache: false, crossDomain: true, url: "http://localhost:8080/customers", type: "POST", dataType:"json", contentType:"application/json", data:JSON.stringify($customer), success: function(data) { console.log(data); alert(data); }, error: function (msg, url, line) { console.log(msg); alert(msg.responseText);//添加客户信息成功弹出消息 //alert('msg = ' + msg + ', url = ' + url + ', line = ' + line); } }) }); /** * 上传图片 */ function upload() { if ($("#photoFile").val() == '') { return; } var formData = new FormData(); //获取图片二进制流 formData.append('photo', document.getElementById('photoFile').files[0]); $.ajax({ url: "http://localhost:8080/customers/uploadPhoto", type: "post", data: formData, contentType: false, processData: false, success: function (data) { if (data.type == "success") { } else { alert(data.msg); } }, error: function (data) { alert("上传失败") } }); }
.3.控制器代码
//图片路径URL public String url; //保存图片代码,同时将图片路径赋值给变量url @CrossOrigin @RequestMapping(value = "/customers/uploadPhoto", method = RequestMethod.POST) @ResponseBody public Map<String, String> uploadPhoto(MultipartFile photo, HttpServletRequest request) { Map<String, String> ret = new HashMap<String, String>(); if (photo == null) { ret.put("type", "error"); ret.put("msg", "选择要上传的文件!"); return ret; } if (photo.getSize() > 1024 * 1024 * 10) { ret.put("type", "error"); ret.put("msg", "文件大小不能超过10M!"); return ret; } //获取文件后缀 String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".") + 1, photo.getOriginalFilename().length()); if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) { ret.put("type", "error"); ret.put("msg", "请选择jpg,jpeg,gif,png格式的图片!"); return ret; } //获取项目根目录加上图片目录 webapp/static/imgages/upload/ String savePath = "C:\\img\\"; System.out.println(savePath); File savePathFile = new File(savePath); if (!savePathFile.exists()) { //若不存在该目录,则创建目录 savePathFile.mkdir(); } String filename = new Date().getTime() + "." + suffix; try { //将文件保存指定目录 photo.transferTo(new File(savePath + filename)); } catch (Exception e) { ret.put("type", "error"); ret.put("msg", "保存文件异常!"); e.printStackTrace(); return ret; } ret.put("type", "success"); ret.put("msg", "上传图片成功!"); ret.put("filepath","C:\\img\\"); ret.put("filename", filename); System.out.println(filename); url=savePath+filename; return ret; } //添加客户信息的代码 @CrossOrigin @RequestMapping(value = "/customers", method = RequestMethod.POST, headers = "Accept=application/json") public ResponseEntity<Object> addCustomer(@RequestBody Customer customer) { customer.setUrl(url); customerMapper.insert(customer); url=null; return new ResponseEntity<>("添加成功", HttpStatus.CREATED); }