文件上传
文件的上传本质上是对流(IO流)的操作。
文件上传的介绍
(1)文件上传,也称为upload,是指将本地图片、视频、视频等文件上传到服务器上,可以提供其他用户浏览或者下载的一个过程。
(2)文件上传时,对页面的form有如下要求:
- 采用post方式提交数据: method=“post”
- 采用multipart格式上传文件 enctype=“multipart/form-data”
- 使用input的file控件上传
(3)文件上传的底层原理都是基于form表单的文件上传。
(4)服务端要接收客户端页面上传的文件,通常都会使用Apache的两个组件:
- commons-fileupload
- commons-io
(5)Spring框架在Spring-web包中对文件上传进行了封装,大大简化了服务端代码,只需要在Controller的地方中声明一个MultipartFile类型的参数即可接收上传的文件。
代码实现
- 新建一个CommonController类:文件上传下载的业务控制层----->服务端
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
}
- 在该CommonController类中编写文件上传代码:
@Value("${reggie.path}")
private String basePath;
/**
* 文件上传
* @param file
* @return
*/
@PostMapping("/upload")
public R<String> upload(MultipartFile file) { //此参数的名字必须与前端的name的值保持一致
//file是一个临时文件,需要转存到指定位置,否则本次请求完成后临时文件会被删除
log.info(file.toString());
//获得原始文件名,即上传时的文件名
String originalFilename = file.getOriginalFilename();
//截取原始文件名的后缀(如:.jpg)
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新随机生成文件名,防止文件名称重复造成文件覆盖
String fileName = UUID.randomUUID().toString() + suffix;
//创建一个目录对象
File dir = new File(basePath);
//判断当前目录是否存在
if(!dir.exists()) {
//目录不存在,需要创建
dir.mkdirs();
}
try {
// 将临时文件转存到指定位置 transferTo传输
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return R.success(fileName);
}
- application.yml文件中添加:
#文件上传下载的配置
reggie:
path: E:\img\ #指定文件上传存放的目录
- 文件上传下载页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="../../plugins/element-ui/index.css" />
<link rel="stylesheet" href="../../styles/common.css" />
<link rel="stylesheet" href="../../styles/page.css" />
</head>
<body>
<div class="addBrand-container" id="food-add-app">
<div class="container">
<!-- ElementUI提供的upload上传组件 -->
<!-- action="":指定请求的地址-->
<el-upload class="avatar-uploader"
action="/common/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeUpload"
ref="upload">
<!-- 展示图片 -->
<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/index.js"></script>
<script>
new Vue({
el: '#food-add-app',
data() {
return {
imageUrl: ''
}
},
methods: {
handleAvatarSuccess (response, file, fileList) {
this.imageUrl = `/common/download?name=${response.data}`
},
beforeUpload (file) {
if(file){
const suffix = file.name.split('.')[1]
const size = file.size / 1024 / 1024 < 2
if(['png','jpeg','jpg'].indexOf(suffix) < 0){
this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
this.$refs.upload.clearFiles()
return false
}
if(!size){
this.$message.error('上传文件大小不能超过 2MB!')
return false
}
return file
}
}
}
})
</script>
</body>
</html>
功能测试
启动SpringBootApplication启动类。
文件下载
文件的x下载本质上也是对流(IO流)的操作。
文件下载介绍
(1)文件下载,也称download,是指将文件从服务器传输到本地计算机的过程。
(2)通过浏览器进行文件下载,通常有两种表现形式:
-
以附件形式下载,弹出保存对话框,将文件保存到指定的磁盘目录
-
直接在浏览器中打开
(3)通过浏览器进行文件下载,本质上就是服务端将文件以流的形式写回浏览器的过程。
代码实现
- 在CommonController类中添加:
/**
* 文件下载
* @param name
* @param response
*/
@GetMapping("/download")
public void download(String name, HttpServletResponse response) {
try {
//输入流,通过输入流读取文件内容
FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
//输出流,通过输出流将文件写回浏览器,在浏览器展示图片
ServletOutputStream outputStream = response.getOutputStream(); //向前端响应对象
//设置下载后的文件类型
response.setContentType("image/jpeg");
int len = 0;
byte[] bytes = new byte[1024];
while((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
//关闭资源
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}