AJAX 上传图片到磁盘并通过restful保存图片路径到数据库 添加客户操作


1.form表单,包括其他字段

//photoFile绑定函数内的代码获取二进制数据

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 uploadPhoto(MultipartFile photo, HttpServletRequest request) {
        Map ret = new HashMap();
        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 addCustomer(@RequestBody Customer customer) {
		customer.setUrl(url);
		customerMapper.insert(customer);
		url=null;
		return new ResponseEntity<>("添加成功", HttpStatus.CREATED);
	}