赞
踩
一个方法将文件上传到项目本地
使用element ui实现文件上传:
<el-upload class="avatar-uploader" action="http://localhost:8888/api/file/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" > <img v-if="imageUrl" :src="imageUrl" class="avatar" /> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> <script> handleAvatarSuccess(res, file) { if (res.code == "200") { this.imageUrl = URL.createObjectURL(file.raw); } }, beforeAvatarUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!"); } if (!isLt2M) { this.$message.error("上传头像图片大小不能超过 2MB!"); } return isJPG && isLt2M; }, </script>
控制器:
@PostMapping("/upload")
public PublicResponse upload(MultipartFile file) {
String fileName = fileService.upload(file);
return PublicResponse.success(fileName);
}
方法实现:
@Override public String upload(MultipartFile multipartFile) { // 判断文件是否为空 if (ObjectUtils.isEmpty(multipartFile)) { log.info("文件为空!"); return "error"; } // 获取文件后缀 final String fileSuffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1); // 新文件名 final String fileName = UUID.randomUUID() + "." + fileSuffix; String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + LocalDate.now(); File file = new File(path, fileName); if (!file.exists()) { file.mkdirs(); } try { multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } return path.substring(1) + "/" + fileName; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。