需求:
跨服务器上传图片,页面不刷新,图片即时回显。
跨服务器上传图片: jersy
页面不刷新: ajax
图片即时回显: <img src =“”/>
1.导入上传文件以及jersy相关依赖
commons-fileupload-1.3 .jar
commons-io-2.5.jar (fileupload依赖于这个jar包 所以不需要再导入)
jersey-core-1.18.1.jar (client依赖这个jar包,所以不需要额外导入
jersey-client-1.18.1.jar
2.开启两个服务器
一个作为java程序的服务器;
另一个作为图片服务器,在WebRoot下创建img文件夹;
并修改该服务器的三个端口号以保证不冲突(server.xml):8005,8080,8009;
修改该服务器的只读权限(web.xml)
3.jsp:引入 jquery文件
jquery-3.1.1.min.js
4.还需要在springmvc的配置文件中配置文件解析器:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000"/>
</bean>
跨服务器上传图片: jersy
页面不刷新: ajax
图片即时回显: <img src =“”/>
1.导入上传文件以及jersy相关依赖
commons-fileupload-1.3 .jar
jersey-client-1.18.1.jar
2.开启两个服务器
一个作为java程序的服务器;
另一个作为图片服务器,在WebRoot下创建img文件夹;
并修改该服务器的三个端口号以保证不冲突(server.xml):8005,8080,8009;
修改该服务器的只读权限(web.xml)
3.jsp:引入 jquery文件
jquery-3.1.1.min.js
4.还需要在springmvc的配置文件中配置文件解析器:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000"/>
</bean>
<html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <head> <title>Title</title> </head> <SCRIPT src="jquery-3.3.1.min.js"></SCRIPT> <script src="jquery.form.js"></script> <style> #img_to_show:hover { /*鼠标样式*/ cursor: pointer; } </style> <body> <h2>Register!</h2> <form id="form1" action="/user/register" method="post"> <img id="img_to_show" width="50px" height="50px" src="http://127.0.0.1:8088/img/default.png" onclick="select_img()"> <br> <input type="file" name="img" onchange="upload_img()" style="display: none"> <br> username: <input name="username"> <br> password:<input type="password" name="password"> <br> <input name="photo " value="" type="hidden"> <button>register</button> </form> </body> <script> function upload_img() { //异步提交表单 //$(提交的表单).ajaxSubmit() //表单插件语法: $("#form1").ajaxSubmit({ type: 'post', url: '/upload', success: function (path) { //2.获取上传后的图片路径 // alert(path); $("#img_to_show").prop("src", path) //3.修改图片路径表单项的value $("input[name=photo]").val(path) } }) } function select_img() { $("input[name='img']").click(); } </script> </html>
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class UploadController { @RequestMapping("/upload") public void upload(@RequestParam("img") CommonsMultipartFile file, HttpServletResponse response) throws IOException { System.out.println(file.getSize()); //1.获取客户端对象 Client client = Client.create(); //2.连接资源 String imgPath = "http://127.0.0.1:8088/img/2.jpg"; WebResource resource = client.resource(imgPath); //把资源传过去 resource.put(file.getInputStream()); response.getWriter().print(imgPath); } }