文件上传
@RequestMapping("upload")
public String upload(MultipartFile m,HttpServletRequest request)
{
//获取上传到的文件夹
String Path = request.getRealPath("/upload");
//通过时间获取文件名称
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSSS");
String format = sdf.format(new Date());
//后缀名
String ext = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf("."));
//一个新的文件
File file=new File(Path+"/"+format+ext);
try {
//将数据复制到新的文件中
FileUtils.copyInputStreamToFile(m.getInputStream(), file);
}catch (Exception e){
e.printStackTrace();
}
return "index";
}
配置文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxInMemorySize" value="2097152"></property>
<!--2097152/1024/1024=2mb-->
</bean>
jsp
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/upload.action" method="post" enctype="multipart/form-data">
上传:<input type="file" name="m"><!--name要与方法中属性一样-->
<input type="submit" value="上传">
</form>
</body>
</html>
所有upload文件夹下所有路径显示在视图
@RequestMapping("files")
public ModelAndView files(HttpServletRequest request){
String path = request.getRealPath("/upload");
File file=new File(path);
//获取目录下的所有子文件
File[] files = file.listFiles();
ModelAndView m=new ModelAndView();
m.addObject("files",files);
m.setViewName("files");
return m;
}
}
files.jsp
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:forEach items="${files}" var="f">
<a href="/download.action?fileName=${f.name}">点击下载</a>
</c:forEach>
</body>
</html>
下载
//下载
@RequestMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request,String fileName){
String path = request.getRealPath("/upload");
File file=new File(path+"/"+fileName);
byte[] b=null;
try {
InputStream is=new FileInputStream(file);
b=new byte[is.available()];
is.read(b);
}catch (Exception e){
e.printStackTrace();
}
//创建http的响应头部信息 (告诉浏览器需要做什么操作)
HttpHeaders headers=new HttpHeaders();
//设置要下载的文件的显示名称
headers.setContentDispositionFormData("attchement",file.getName());
//设置下载的时候输出的数据类型 以二进制字节流的形式输出数据
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> entity=new ResponseEntity<>(b,headers, HttpStatus.OK);
return entity;
}