关于ssm整合请看我的第一篇,这里只讲文件上传与下载
首先加入相关依赖:
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
在spring配置文件中加入文件配置:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 上传图片最大大小5M -->
<property name="maxUploadSize" value="5242440"></property>
</bean>
整个项目目录如图:
在数据库中新建表,表结构如下:
Upfile.java:
package com.test.model; import org.springframework.stereotype.Component; @Component public class UpFile { private int id; private String filename; private String filepath; public UpFile() { super(); } public UpFile(int id, String filename, String filepath) { super(); this.id = id; this.filename = filename; this.filepath = filepath; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } @Override public String toString() { return "UpFile [id=" + id + ", filename=" + filename + ", filepath=" + filepath + "]"; } }
UpFileMapper.java:
package com.test.mapper; import java.util.List; import com.test.model.UpFile; public interface UpFileMapper { UpFile selectFileById(int id); void InsertUpFile(UpFile upFile); List<UpFile> selectAllFile(); }
UpFileMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.test.mapper.UpFileMapper"> <resultMap type="UpFile" id="UpFileBean"> <id column="id" property="id" /> <result column="filename" property="filename" /> <result column="filepath" property="filepath" /> </resultMap> <select id="selectFileById" resultMap="UpFileBean"> select * from upfile where id=#{id} </select> <insert id="InsertUpFile" parameterType="UpFile"> insert into upfile (filename,filepath) values (#{filename},#{filepath}) </insert> <select id="selectAllFile" resultType="UpFile"> select * from upfile </select> </mapper>
FileService.java:
package com.test.service; import java.util.List; import com.test.model.UpFile; public interface FileService { UpFile selectFileById(int id); void InsertUpFile(UpFile upFile); List<UpFile> selectAllFile(); }
FileServiceImpl.java:
package com.test.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.mapper.UpFileMapper; import com.test.model.UpFile; @Service public class FileServiceImpl implements FileService{ @Autowired UpFileMapper upFileMapper; @Override public UpFile selectFileById(int id) { // TODO Auto-generated method stub return upFileMapper.selectFileById(id); } @Override public void InsertUpFile(UpFile upFile) { // TODO Auto-generated method stub upFileMapper.InsertUpFile(upFile); } @Override public List<UpFile> selectAllFile() { // TODO Auto-generated method stub return upFileMapper.selectAllFile(); } }
FileController.java:
package com.test.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.test.model.UpFile; import com.test.service.FileService; @RequestMapping("/file") @Controller public class FileController { @Autowired FileService fileService; @RequestMapping("/fileup") //参数中的files要和页面中input输入框的name值相同 public String fileup(MultipartFile[] files, HttpServletRequest request) throws IllegalStateException, IOException { //获取文件上传路径 String path = request.getSession().getServletContext().getRealPath("upload"); System.out.println(path); StringBuffer stringBuffer=new StringBuffer(); for (MultipartFile multipartFile : files) { if(!multipartFile.isEmpty()) { //将多个文件名拼接在一个字符串中,用;分隔 stringBuffer.append(multipartFile.getOriginalFilename()); stringBuffer.append(";"); File dir=new File(path, multipartFile.getOriginalFilename()); if(!dir.exists()) { dir.mkdirs(); } multipartFile.transferTo(dir); } } //去除最后一个;号 String s=stringBuffer.substring(0, stringBuffer.length()-1); //存入数据库 fileService.InsertUpFile(new UpFile(0, s, path)); System.out.println(s); //重定向至显示页面 return "redirect:/file/showallfiles"; } @RequestMapping("/showallfiles") public String showAllFile(Model model) { //获取所有文件 List<UpFile> allfiles=fileService.selectAllFile(); //新建map存储文件id和name,其中id作为键 HashMap<String, Object> map=new HashMap<>(); for (UpFile upFile : allfiles) { //分割文件名字符串,将每个文件名添加到list中, List<String> filenamelist=new ArrayList<>(); String[] filenamearr=upFile.getFilename().split(";"); for (String string : filenamearr) { filenamelist.add(string); } //list作为map的值 map.put(upFile.getId()+"", filenamelist); } model.addAttribute("files", map); return "showfile"; } @ResponseBody @RequestMapping("/downfile") public String downfile(String filename,String id,HttpServletRequest request,HttpServletResponse response) throws IOException { System.out.println(filename+id); //根据id获取文件上传路径 UpFile upFile=fileService.selectFileById(Integer.parseInt(id)); String fileName = upFile.getFilepath()+"/"+filename; //防止中文乱码 filename = URLEncoder.encode(filename,"UTF-8"); System.out.println(filename); //获取输入流 InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName))); //设置文件下载头 response.addHeader("Content-Disposition", "attachment;fileName=" + filename); //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); return "OK"; } }
在index.html中编写上传页面:
<%@ 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>
<form action="file/fileup" method="post" enctype="multipart/form-data">
<input type="file" name="files" value="文件一"/>
<input type="file" name="files" value="文件二"/>
<input type="file" name="files" value="文件三"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
在/WEB-INF/views/目录下新建showfile.html:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<table>
<c:forEach items="${files }" var="file">
<tr>
<td>${file.key}</td>
<td>
<c:forEach items="${file.value}" var="filename">
<ul>
<li><a href="/ssm/file/downfile?filename=${filename}&id=${file.key}">${filename}</a></li>
</ul>
</c:forEach>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
最后,开启tomcat,输入网址:http://localhost:8080/ssm/
上传两个文件:
点击文件名下载:
结束!