购物商城之图片服务器:1.图片上传,2进制图片数据到图片服务器。2.需要的jar。
com.sun.jersey jersey-client 1.18.1
3.复制一个tomcat作为图片服务器
4.代码实现
// 上传图片 @RequestMapping(value = "/upload/uploadPic.do") // RequestParam(required=false)参数pic 可以上传,也可以不上传 public void uploadPic(@RequestParam(required = false) MultipartFile pic, HttpServletResponse response) { // pic.getOriginalFilename() 1.png // 获取文件扩展名 String ext = FilenameUtils.getExtension(pic.getOriginalFilename()); // 图片名称生成策略 DateFormat dFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String format = dFormat.format(new Date()); // 随机三位数 Random random = new Random(); // random.nextInt(100)+100// n 100 0-99 for (int i = 0; i < 3; i++) { format += random.nextInt(10); } // 实例化一个jersey Client client = new Client(); // 保存数据库的相对路径 String path = "upload/" + format + "." + ext; // 图片服务器请求路径 Constans.IMGSERVICE是图片服务器地址常量 // // 图片服务器地址 //public static final String IMGSERVICE = "http://localhost:8081/image-web/"; // 设置请求路径 String url = Constans.IMGSERVICE + path; // 发送图片到服务器 WebResource resource = client.resource(url); try { // pic.getBytes() 图片的字节数组内容 resource.put(String.class, pic.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 异步放返回数据 JSONObject jo = new JSONObject(); jo.put("url", url); jo.put("path", path); //自己写的工具类 ResponseUtils.renderJson(response, jo.toString()); }
页面
function uploadPic() { //定义参数 var options = { url : "/upload/uploadPic.do", dataType : "json", type : "post", success : function(data){ //回调 二个路径 //url 显示路径 //path 相对路径 $("#allImgUrl").attr("src",data.url); $("#path").val(data.path); } }; //jquery.form使用方式 $("#jvForm").ajaxSubmit(options); }