-
Vue页面
具体参考官网网址:https://www.antdv.com/components/upload-cn/ -
action中的 /crmapi 是我在vue的配置中对后台方法引入调用时的前缀限制
<template>
<a-upload
name="file"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
action="/crmapi/upload/uploadPic"
:before-upload="beforeUpload"
@change="handleChange"
>
<img v-if="imageUrl" :src="imageUrl" alt="avatar" />
<div v-else>
<a-icon :type="photoLoading ? 'loading' : 'plus'" />
<div class="ant-upload-text">
Upload
</div>
</div>
</a-upload>
</template>
<script>
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
export default {
data() {
return {
photoLoading: false,
imageUrl: '',
};
},
}
methods: {
handleChange(info) {
console.log(info)
if (info.file.status === 'uploading') {
this.photoLoading = true;
return;
}
if (info.file.status === 'done') {
console.log(info.file.originFileObj)
getBase64(info.file.originFileObj, imageUrl => {
this.imageUrl = imageUrl;
this.photoLoading = false;
});
this.file = info.file.originFileObj
}
},
beforeUpload(file) {
console.log(file)
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
this.$message.error('You can only upload JPG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
},
}
</script>
- 配置文件配置信息
#图片上传
spring.servlet.multipart.enabled=true
#单个数据的大小
spring.servlet.multipart.max-file-size=3MB
#总数据的大小
spring.servlet.multipart.max-request-size=3MB
#文件夹路径
pic_path=D:\\pic
- 后台方法代码
@RestController
@RequestMapping("/upload")
public class CheckController {
@Value("${pic_path}")
private String pic_path;
/**
* 图片上传
* @param file 图片对象
*/
@PostMapping("/uploadPic")
public String uploadPic(@RequestParam MultipartFile file, HttpServletRequest request) throws Exception {
// 文件路径
String path = "";
// 判断上传的文件是否为空
if (file != null) {
String type = "";
String fileName = file.getOriginalFilename();// 文件原名称
// 获取文件类型
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
// 文件类型不为空时
if (type != null) {
//过滤文件类型
if ("PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
// 自定义的文件名称
String newFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
//判断所存放文件夹是否存在,不存在则创建
File dir = new File(pic_path);
if (!dir.exists()) {
dir.mkdirs();
}
//图片存放路径
path = pic_path+"\\"+fileName;
// 转存文件到指定的路径
file.transferTo(new File(path));
return "图片上传成功";
}
} else {
return "图片类型错误";
}
} else {
return "图片不可为空";
}
return "图片上传失败";
}
}