1.前台界面代码
<form id="jvForm" action="add.do" method="post" enctype="multipart/form-data"> <table> <tr> <td width="20%" class="pn-flabel pn-flabel-h"></td> <td width="80%" class="pn-fcontent"> <img width="100" height="100" id="allImgUrl" /> <input type="hidden" name="imgUrl" id="path" /> <input type="file" onchange="uploadPic()" name="pic" id="logoPic"/> </td> </tr> </table> </form>
2.前台JS代码
<script type="text/javascript"> //上传图片 function uploadPic() { //定义参数 var options = { url : "/upload/uploadPic.do", dataType : "json", type : "post", beforeSubmit : function(formData,jqForm,options){ // 判断是否为图片 // 将jqForm转成DOM对象 var f = jqForm[0]; // 获取DOM对象中name为logoPic的值 var v = f.logoPic.value; // 获取扩展名,并转成小写 var ext = v.substring(v.length-3).toLowerCase(); // 比对扩展名 jpg gif bmp png if(ext != "jpg" && ext != "gif" && ext != "bmp" && ext != "png"){ alert("只允许上传图片!"); return false; } //校验提交的表单 return true; }, success : function(data) { // 回显图片内容 $("#allImgUrl").attr("src", data.url); $("#path").val(data.path); } }; // jquery.form使用方式 $("#jvForm").ajaxSubmit(options); } </script>
3.在Spring中配置图片转换器
<!-- 上传图片转换器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为1MB --> <property name="maxUploadSize" value="1048576"/> </bean>
4.创建UploadController以及工具类
package cn.itcast.core.controller.admin; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import cn.itcast.common.web.ResponseUtils; import cn.itcast.core.web.Constants; @Controller public class UploadController { // 上传图片 @RequestMapping(value = "/upload/uploadPic.do") public void uploadPic(@RequestParam(required = false) MultipartFile pic, HttpServletResponse response) { // 扩展名 String ext = FilenameUtils.getExtension(pic.getOriginalFilename()); // 图片名称生成策略 DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); // 图片名称一部分 String format = df.format(new Date()); // 随机三位数 Random r = new Random(); // n 1000 0-999 99 for (int i = 0; i < 3; i++) { format += r.nextInt(10); } // 实例化一个Jersey Client client = new Client(); // 保存数据库 String path = "upload/" + format + "." + ext; // 另一台服务器的请求路径是? String url = Constants.IMAGE_URL + path; // 设置请求路径 WebResource resource = client.resource(url); // 发送开始 POST GET PUT try { resource.put(String.class, pic.getBytes()); } catch (IOException e) { e.printStackTrace(); } // 返回二个路径 JSONObject jsonObject = new JSONObject(); jsonObject.put("url", url); jsonObject.put("path", path); ResponseUtils.renderJson(response, jsonObject.toString()); } }
package cn.itcast.core.web; public interface Constants { /** * 图片服务器 */ public static final String IMAGE_URL = "http://localhost:8088/BabasportProject_ImageService/"; }
package cn.itcast.common.web; import java.io.IOException; import javax.servlet.http.HttpServletResponse; public class ResponseUtils { // 发送内容 public static void render(HttpServletResponse response, String contentType, String text) { response.setContentType(contentType); try { response.getWriter().write(text); } catch (IOException e) { e.printStackTrace(); } } // 发送的是JSON public static void renderJson(HttpServletResponse response, String text) { render(response, "application/json;charset=UTF-8", text); } // 发送xml public static void renderXml(HttpServletResponse response, String text) { render(response, "text/xml;charset=UTF-8", text); } // 发送text public static void renderText(HttpServletResponse response, String text) { render(response, "text/plain;charset=UTF-8", text); } }
5.搭建另一个Tomcat,作为图片服务器
图片服务器Tomcat的设置 tomcat/conf/web.xml中内容更改
<servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>readonly</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>listings</param-name> <param-value>false</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
6.Eclipse上创建JavaWeb项目,取名BabasprotProject_ImageService
7.修改图片服务器的Tomcat的端口号
8.在BabasprotProject_ImageService项目的webapp目录下创建upload文件夹
======================
启动服务器 测试是否成功
======================
本文出自 “Java开发工程师” 博客,请务必保留此出处http://robertohuang.blog.51cto.com/10343725/1846554
原文地址:http://robertohuang.blog.51cto.com/10343725/1846554