承接上一篇(文件上传下载的实现SSM):https://blog.csdn.net/Tianc666/article/details/104581182
注解已经很清晰了,主要我要说道说道 fileName、allfilename 这两个全局变量。
filename是在上传的时候从前台接收用户名创建的;
allfilename是把上面的filename放到集合里面的,显示到前台中下载按钮前面的。
为什么这里要用全局变量呢?因为每次刷新页面的时候,我要把“/file/upload” 中 add 进 allfilename 里的文件名的集合通过“/file/FilePage”接口发送到前台解析出来,并且循环输出,再把对应的下载按钮前面的文件名传回后台,进行下载操作。
上代码:
/**
* 跳转文件上传下载页面
*/
//获取当此上传文件名
String fileName = null;
//存储每一次上传的文件名
List<Object> allfilename = new ArrayList<>();
@RequestMapping("/file/FilePage")
public String FilePage(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute("file",allfilename);
return "FilePage";
}
/**
* 文件上传功能
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/file/upload",method=RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file) throws IOException {
//得到上传文件名
fileName = file.getOriginalFilename();
//存储每一次上传的文件名
allfilename.add(fileName);
//文件上传地址
String path = "F:\\file";
//创建文件流
File dir = new File(path,fileName);
//如果父目录不存在,连同父目录一起创建。
if(!dir.exists()){
dir.mkdirs();
}
//MultipartFile自带的解析方法
file.transferTo(dir);
return "ok!";
}
/**
* 文件下载功能
* @param response
* @throws IOException
*/
@RequestMapping(method =RequestMethod.GET ,value = "/file/down")
public void down(HttpServletResponse response,String downname) throws IOException {
//文件路径
String path = "F:\\file\\"+downname;
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
//转码,免得文件名中文乱码
path = URLEncoder.encode(path,"UTF-8");
//设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downname,"UTF-8"));
//设置文件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();
}