首先是设置一下tomcat的虚拟路径,有两种方法(以在C:/upfile/为例)
- 第一种是在tomcat的bin目录下的server.xml添加一句
< Context docBase=“C:/upfile/” path="/upload" reloadable=“false”/>
/upload就是虚拟路径,在下面的文件可以在浏览器localhost:8080 /upload/。。。访问到
- 第二种是在idea下的简单设置,如下
访问localhost:8080/upfile/404.jpg
编写一个简单的文件上传页面uploadPictureJsp.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/10/23
Time: 13:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传图片</title>
</head>
<body>
<form action="/upfile.do" method="post" enctype="multipart/form-data">
<c:if test="${picture!=null}">
<img src="/upfile/${picture}" width="100px" height="100px">
</c:if>
<input type="file" name="picture">
<input type="submit">
</form>
</body>
</html>
然后就是控制器类uploadFile,放在/uploadPicture下
需要导入两个包
package uploadPicture;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* Created by Administrator on 2018/10/23.
*/
@Controller
public class uploadFile {
@RequestMapping("/upfile.do")
public String upfile(Model model, HttpServletRequest request, MultipartFile picture)
throws IOException {
// String picrureName=request.getParameter("picture");
request.setAttribute("picture",picture.getOriginalFilename());
String picName= UUID.randomUUID().toString();
String oriName=picture.getOriginalFilename();
String extName=oriName.substring(oriName.lastIndexOf("."));
picture.transferTo(new File("C:/upfile1/"+picName+extName));
System.out.println(request.getParameter("picture"));
return "forward:/uploadPictureJsp.jsp";
}
}
需要在springmvc的配置文件demo1.xml配置一下
<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件上传大小 5M -->
<property name="maxUploadSize" value="5000000" />
</bean>
ok,简单的上传文件的demo完成了