ElementUI+springboot上传文件

2020-11-06 08:01:39 浏览数 (1)

ElementUI springboot上传文件

配置上传路径

image.properties

代码语言:javascript复制
image.localDirPath=/Volumes/mac/Program/PageImg/

实现

代码语言:javascript复制
@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("文件不合法")
}
    }

前端部分

代码语言:javascript复制
<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>

0 人点赞