里面包含了文件上传下载并解决上传与下载文件中文乱码的问题,运用正则表达式判断字符串中是否包含中文和得到一个文件夹下的所有文件的方法,几乎集合了上传下载所需要的所有东西.下面代码加红的部分就是这几个重要点!
知识要大家一起分享嘛.
首先,需要配置好Spring+Springmvc的环境
1.在maven中添加: 如果你不是用maven管理项目的话,就百度Multipartfile所需的jar包即可,然后添加上jar包即可
<!--文件上传下载支持jar包--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency>
2.在你配置视图解析器的xml里面添加:
<!-- 定义文件解释器 --> <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>
2.新建一个测试页面
<%@ 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=ISO-8859-1"> <title>文件上传下载</title> </head> <body> <form action="uploadstudent" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="file" width="120px"> <input type="submit" value="上传"> </form> <hr> <form action="downstudent" method="get"> 文件名:<input type="text" name="filename"> <input type="submit" value="下载"> </form> </body> </html>3.新建一个controller页面
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Controller
public class FileController {
/**
* 前台得到教师上传的文件名 用于学生下载文件
* @param request
* @return
*/
@RequestMapping("/getAllFileStudent")
public File[] GetAllFileNameStudnet(HttpServletRequest request){
//得到路径
String path = request.getSession().getServletContext().getRealPath("importantFile");
File file = new File(path);
//得到该路径下的所有文件的属性
File[] array = file.listFiles();
return array;
}
/**
* 前台得到学生上传的文件名 用于教师下载文件
* @param request
* @return
*/
@RequestMapping("/getAllFileTeacher")
public File[] GetAllFileNameTeacher(HttpServletRequest request){
//得到路径
String path = request.getSession().getServletContext().getRealPath("uploadFile");
File file = new File(path);
File[] array = file.listFiles();
return array;
}
/**
* 学生文件上传功能
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/uploadstudent",method= RequestMethod.POST)
@ResponseBody
public String uploadStudent(MultipartFile file, HttpServletRequest request) throws IOException{
//设置路径,该语句会自动的在该项目的target里面的项目名下的目录里面自动创建文件夹uploadFile,用于存放上传文件
String path = request.getSession().getServletContext().getRealPath("uploadFile");
//得到上传文件的文件名
String fileName = file.getOriginalFilename();
//创建文件
File dir = new File(path,fileName);
//判断目录是否存在,如果父目录不存在,调用mkdirs方法创建父目录与子目录
if(!dir.exists()){
dir.mkdirs();
}
//MultipartFile自带的解析文件的方法
file.transferTo(dir);
return "上传文件成功!";
}
/**
* 学生文件下载功能
* @param request
* @param response
* @param file
* @throws Exception
*/
@RequestMapping("/downstudent")
public void downStudent(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam("filename") String file) throws Exception{
//模拟文件,获取文件下载路径,file为需要下载的文件名
String fileName = request.getSession().getServletContext().getRealPath("importantFile")+"/"+file;
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//运用正则表达式判断文件名是否含有中文字符,进行转码,避免乱码
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(file);
//判断是否存在 存在进入循环
if (m.find()) {
//转码,避免下载文件时文件名中文乱码
String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? file.getBytes() : file.getBytes("UTF-8"); // file.getBytes("UTF-8")处理safari的乱码问题
file = new String(bytes, "ISO-8859-1");
}
//设置文件下载头
response.addHeader("Content-Disposition", String.format("attachment;filename=" + file));
//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();
}
}
洋仔聊编程 认证博客专家 认证博客专家 开源爱好者 研发工程师 知识是永远的流行色!博主分享工作中涉及到的技术知识,包含Java技术干货(JVM+并发+全链路优化)、计算机网络、数据结构与算法、linux等编程知识;欢迎关注!共同进步!