文件上传介绍



文件上传代码实现

page>demo>复制upload.html
<!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>
<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>
查看效果


当我们选择一张图片的时候,他会自动的发送请求到服务端,所以下面编写服务端,来处理这个请求
新建CommonController类
主要进行文件的上传和下载
package com.taotao.reggie.controller;
import com.taotao.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@PostMapping("/upload")
public R<String> upload(MultipartFile file){
return null;
}
}
注意,此file参数必须要与payload中name = 'file’一致

断点测试
可以看到,这个文件目前是个临时文件状态,所以我们给他转存一下,否则本次请求完成后,这个临时文件会消失

尝试寻找临时文件

上传文件时传输的临时文件,被存放在c盘的temp内的更深的文件夹中
这个temp文件夹是我清理c盘时必清的文件夹,他就是系统缓存文件夹
这就是我们上传和下载文件的一个过程吧,他需要那么一个tmp类型文件来进行交互,当我们得到源文件时,这个tmp文件才会消失

转存文件
file.transferTo(new File(“D:\dishs”));
package com.taotao.reggie.controller;
import com.taotao.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@PostMapping("/upload")
public R<String> upload(MultipartFile file){
log.info(file.toString());
try {
file.transferTo(new File("D:\\dishs.jpg"));
} catch (IOException e) {
System.out.println("转存文件失败...");
e.printStackTrace();
}
return null;
}
}
取消拦截器过滤LoginCheckFilter.java
添加common/**,使common文件夹下资源不用登陆也可以使用

运行测试
转存成功

完善功能
配置准确路径
编写application.xml

编写CommonController.java


运行测试
成功

完善二级目录
编写application.yml

编写CommonControler.java
package com.taotao.reggie.controller;
import com.taotao.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@Value("${reggie.path}")
private String basePath;
@PostMapping("/upload")
public R<String> upload(MultipartFile file){
log.info(file.toString());
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + suffix;
File dir = new File(basePath);
if(!dir.exists()){
dir.mkdir();
}
try {
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
System.out.println("转存文件失败...");
e.printStackTrace();
}
return R.success(fileName);
}
}
测试成功

|