这篇文章,我们将来讲一讲SpringMVC如何实现文件的上传操作。
1. 文件上传
1.1 导入相关的jar包(代码如下):
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
截图如下:
1.2 写Controller中的方法
下面,我们一起来看一下Controller中的方法如何写,代码如下:
/***
* 页面跳转
* @return
*/
@RequestMapping("/toFile")
public String toFile(){
return "FileUploadAndDown";
}
/**
* 文件上传功能
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value="/upload",method= RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
// uploads文件夹位置
String rootPath = request.getSession().getServletContext().getRealPath("WEB-INF/upload");
// 原始名称
String originalFileName = file.getOriginalFilename();
// 新文件
File newFile = new File(rootPath + File.separator + File.separator + originalFileName);
// 判断目标文件所在目录是否存在
if( !newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
System.out.println(newFile);
// 将内存中的数据写入磁盘
file.transferTo(newFile);
return "{\"data\":\"success\"}";
}
截图如下:
解释:
第24行:做的是一个页面跳转。起始页面有一个页面跳转的触发器,点击之后会跳转到文件上传的页面
第35行:有一系列的入参,有java自带的文件类。
第37行:定义了String类型的rootPath,放的是文件上传完成后的地址,即:WEB-INF/upload
第39行:定义String类型的originalFileName,获取文件的原始名称
第41行:我们new一个新文件,文件的地址就是我们要上传的地址,文件的名称就是上传文件的名称,文件的类型和内容就是上传文件的类型和内容。从这一步我们可以看出,文件上传的本质就是将文件复制一份放到另一个位置,其中文件复制的这个过程由java自带的类去实现,不用我们去写,我们只需要调用这些类的相关方法就好。
第43行:判断一下目标文件所在目录是否存在
第45行:如果目标文件所在目录不存在,那就创建一个
第47行:输出一下新文件的地址和名称
第49行:将内存中的数据写入磁盘
第50行:上传完成后的显示字段
1.3 上传的页面书写
下面,我们看一下文件上传的页面书写(代码如下):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传页面</title>
</head>
<body>
<h3>文件上传</h3>
<form id="addForm" action="/New_SpringMVCDemo_02/file/upload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file" width="120px">
<input type="submit" value="上传">
</form>
<div id="upMenu" class="white_content">
<form id="downForm" lay-filter="updata" action="/New_SpringMVCDemo_02/file/down" method="get">
<input type="text" id="filename" name="filename">
<input type="submit" value="下载">
</form>
<input type="button" value="完成"/>
</div>
</body>
</html>
截图如下:
注意:第10-13行是上传的页面,第15-21是文件下载的页面部分
这部分不是太懂,不多说
1.4 运行一下
下面,我们点击运行一下,看一下实验结果。
一切顺利,有些乱码,但问题不大。
2. 文件下载
2.1 Controller中的方法
相关的jar包和其他的一些配置,在实现文件上传的时候就已经配置好了,这里就不需要多说了。下面直接看Controller中的方法(代码如下):
/**
* 文件下载功能
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/down")
public void down(HttpServletRequest request, HttpServletResponse response) throws Exception{
String filename = request.getParameter("filename");
System.out.println(filename);
//模拟文件,myfile.txt为需要下载的文件
String fileName = request.getSession().getServletContext().getRealPath("WEB-INF/upload")+"/"+filename;
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//假如以中文名下载的话
// String filename = "下载文件.txt";
//转码,免得文件名中文乱码
filename = URLEncoder.encode(filename,"UTF-8");
//设置文件下载头
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();
}
2.2 前端页面的书写
其中第15-21行,是下载的页面。
2.3 运行
运行成功!
这是很简单的两个操作。