瑞吉外卖(五)
文件的上传下载
需求分析
-
当点击上传图片时,调用本地文件夹,可以上传jpg、jpeg、bmp等格式的图片;
-
上传完成后,前端页面要得到上传的图片并展示出来。
后端需要做的任务:
3. 读取文件内容,将文件转存到本地
4. 读取刚刚存储的文件,并返回给前端展示。
前端页面设计
<!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">
<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>
文件上传
结合标头中的信息
我们可以看到,采用的是post传输,页面是/common/upload。所以在写的时候,要选择postmapping(“/upload”)注解和requestmapping(“/common”)注解. 从前端获取到的文件要以MultipartFile file参数格式发送过来,形参的命名不能随意命名,要与前端的参数一致,如下图 前端图片 所示,从前端穿的参数命名为file,因此在controller写形参的时候也要用file命名(若在参数前加入@RequestParam(“file”)注解,则可随意命名)。
然后,后端controller获取到文件后,首先读取文件名,为防止重复,为文件生成新的文件名,同时由于从前端传入的文件是临时存放的,因此需要转存到后端的服务器中。
upload代码俠
@Value("${reggie.path}")
private String basePath;
@PostMapping("/upload")
public R<String> upload(@RequestParam("file") MultipartFile file){
// 获取原始文件名
String originalFilename = file.getOriginalFilename();
// 动态获取文件后缀
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// 使用UUID重新生成文件名,防止文件名重复造成文件覆盖
String filename = UUID.randomUUID().toString() + suffix;
//创建一个目录对象
File dir = new File(basePath);
// 判断当前目录是否存在
if (!dir.exists()){
//目录不存在,需要创建
dir.mkdirs();
}
// file 是一个临时文件,需要把它转存在指定位置,否则本次请求完成过后临时文件会被删除
log.info(file.toString());
try {
// 将临时文件转存到指定位置
file.transferTo(new File(basePath+filename));
} catch (IOException e) {
throw new RuntimeException(e);
}
return R.success(filename);
}
注意,为了方便修改,我们可以将文件存储的路径写在application.ymal中。
reggie:
path: D:\img\
文件下载
当文件上传成功后,需求中需要将上传的图片返回到前端页面展示,因此,后端要将图片返回给前端页面展示。
结合前端页面的代码,请求的页面是download,请求方式是Get.
参数,第一个参数就是文件名称,第二个参数就是response用于返回给前端。
方法,读取,然后输出到前端。
代码如下:
/**
* 文件下载
* @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){
//fileInputStream.read(bytes) ,其中bytes用于临时存放读入的字节,当读完之后,返回-1;
outputStream.write(bytes,0,len);
outputStream.flush();
}
// 关闭资源
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
文件上传需要对页面的form表单有如下要求
method = “post” | 采用post方式提交数据 |
---|---|
enctype =“multipart/form-data” | 采用multipart格式上传文件 |
type=“file” | 使用input的file控件上传 |
例如:
<form method="post" action="/common/upload" enctype="multipart/form-data">
<input name = "myFile" type = "file" />
<input type = "submit" value="提交">
</form>