配置上传路径
image.properties
image.localDirPath=/Volumes/mac/Program/PageImg/
实现
@PropertySource("classpath:/image.properties") public class FileServiceImpl implements FileService { @Value("${image.localDirPath}") private String localDirPath; /** * 文件上传 * @param uploadFile * @return */ @Override public ReturnVo fileUpload(MultipartFile uploadFile) { ArrayList<String> strings = new ArrayList<>(); strings.add("image/gif"); strings.add("image/png"); strings.add("image/jpeg"); if (strings.contains(uploadFile.getContentType())){ try { //获取到文件名 String fileName = uploadFile.getOriginalFilename(); //使用日期格式创建文件夹 String dataPathDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date()); //真实的文件夹路径 String realDirPath = localDirPath + dataPathDir; //判断文件夹是否存在 File dirFile = new File(realDirPath); if (!dirFile.exists()){ dirFile.mkdirs(); } String uuid = UUID.randomUUID().toString().replace("-",""); //截取原先文件的类型 String fileType = fileName.substring(fileName.lastIndexOf(".")); String realName = uuid + fileType; //文件上传 String realFilePath = realDirPath + "/" + realName; File file = new File(realFilePath); uploadFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } }else { System.out.println("文件不合法") } }
前端部分
<template> <el-upload :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件,且不超过500kb</div> </el-upload> </template> <script> export default{ data(){ return{ //上传图片地址 uploadUrl:'http://127.0.0.1:8080/upload' } } } </script>
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句