java中文件上传
1、引入maven依赖;
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
将此段依赖写入pom.xml文件中
2、@RequestMapping(value = "index.do",method=RequestMethod.GET)
public String uploadIndex(){
return "upload/index";
}
上传文件首页的后台
3、<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>图片上传</title>
</head>
<body>
<form action="index.do" enctype="multipart/form-data" method="post">
文件上传:<input type="file" name="file" value="请选择文件上传">
<br>
<input type="submit" value="提交"><input type="reset" value="重置">
</form>
</body>
</html>
上传文件的前端页面
1、@RequestMapping(value = "index.do",method = RequestMethod.POST)
public String upload(HttpServletRequest request,MultipartFile file,Model model){
String fileName = file.getOriginalFilename();
String path = "E:/image/";
System.out.println(path);
File dest = new File(path+fileName);
2、try {
file.transferTo(dest);
model.addAttribute("success", true);
model.addAttribute("imageName", fileName);
model.addAttribute("message","文件上传成功");
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
model.addAttribute("success", false);
model.addAttribute("message","文件上传失败");
e.printStackTrace();
}
return "upload/uploadSuccess";
}
上传文件,将文件写入到对应的文件夹,
3、<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>图片上传</title>
</head>
<body>
${message }
<img alt="" src="/uploadImage/${imageName }">
</body>
</htm
对应的上传成功的前端页面
4、tomcat的server.xml配置
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log." suffix=".txt"/>
<!-- 配置虚拟路径 -->
<Context path="/uploadImage" docBase="E:\image\" reloadable="true"></Context>
</Host>
路径不能错;