在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:
<Context docBase="D:\develop\upload\temp" path="/pic" reloadable="false"/>
访问http://localhost:8080/pic即可访问D:\develop\upload\temp下的图片。
复制一张图片到D盘下面的upload问价夹里面,然后使用浏览器访问。
网址为:http://localhost:8080/pic/图片名称(包括后缀名)
实现图片上传需要加入的jar包,如下图:
把两个jar包放到工程的lib文件夹中
在springmvc.xml中配置文件上传解析器
<!-- 文件上传,id必须设置为multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置文件上传大小 单位是B 5M=5*1024*1024 --> <property name="maxUploadSize" value="5242880" /> </bean>
这里我准备两个jsp页面,1个用于文件上传,另外一个用于上传的图片的回显。
1 fileupload.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>FileUpload</title> </head> <body> <form action="${pageContext.request.contextPath }/file/upload.action" method="post" enctype="multipart/form-data"> <input type="file" name="filename"> <input type="submit" value="上传"> </form> </body> </html>
2 uploadsuccess.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>图片上传成功了</h1> <div style="width: 600px;height: 480px;border:2px solid green" > <img alt="图片获取失败" src="/pic/${pictureName}" style="width: 100%;height: 100%"> </div> </body> </html>
package com.test.springmvc.controller; import java.io.File; import java.io.IOException; import java.util.UUID; import javax.jws.WebParam.Mode; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller public class FileController { @RequestMapping(value="/file/upload.action") public void fileUpload(HttpServletRequest request, HttpSession session, HttpServletResponse response, MultipartFile filename) throws Exception{ // 图片上传 // 设置图片名称,不能重复,可以使用uuid String picName =UUID.randomUUID().toString().replaceAll("-", ""); // 获取文件名 String oriName = filename.getOriginalFilename(); // 获取图片后缀 String extName = oriName.substring(oriName.lastIndexOf(".")); // 开始上传 filename.transferTo(new File("E:/upload/" + picName + extName)); //上传后的图片名称 String pictureName = picName+extName; //图片名称放入域中 session.setAttribute("pictureName", pictureName); //重定向图片回显的jsp页面 response.sendRedirect(request.getContextPath()+"/uploadsuccess.jsp"); } }
原文:https://www.cnblogs.com/jepson6669/p/9038914.html