Spring Boot + Vue + Element-UI 实现文件上传

实现上传 .jpg、.png、.pdf 类型的文件。

实现效果如下:

Spring Boot + Vue + Element-UI 实现文件上传_第1张图片

前端代码:


  
请上传经营许可证书
将文件拖到此处,或点击上传
只能上传jpg/png/pdf文件,且不超过2MB
beforeUpload(file) {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isPDF = file.type === "application/pdf";
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG && !isPNG && !isPDF) {
    this.$message.error({
      message: "上传文件格式只能是 JPG PNG PDF 格式!",
      center: true,
    });
  }
  if (!isLt2M) {
    this.$message.error({
      message: "上传文件大小不能超过 2MB!",
      center: true,
    });
  }
  return (isJPG || isPNG || isPDF) && isLt2M;
},
handleSuccess1(res) {
  if (res.code === 1) {
    console.log(res);
    this.$message({
      message: res.message,
      type: "success",
      center: true,
    });
    this.jump1 += 1;
  } else {
    this.$message.error({
      message: "文件上传失败!",
      center: true,
    });
  }
},

后端代码:

1. 实体类

@Data
public class FileEntity implements Serializable {
    /**
     * 文件id
     */
    private String fid;

    /**
     * 文件名
     */
    private String fname;

    /**
     * 文件类型
     */
    private String type;

    /**
     * 文件路径
     */
    private String path;

    private static final long serialVersionUID = 1L;
}

2. Mapper

// FileMapper.java
// 把文件信息存入数据库中
int addFile(FileEntity fileEntity);

// FileMapper.xml


  insert into file (fid, fname, `type`, `path`)
  values (#{fid}, #{fname}, #{type}, #{path})

3. Service

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    // 上传许可证
    @Override
    public Result uploadLicence(MultipartFile file) throws IOException {
        String fid = UUID.randomUUID().toString().replace("-", ""); // 生成文件id(唯一)
        String fname = file.getOriginalFilename(); // 文件名
        String type = fname.substring(fname.lastIndexOf(".")); // 文件类型
        String fullName = fid + type;
        String UPLOAD_DIR = "D:\\Programs\\YogaSystem\\merchant\\file\\licence"; // 上传路径
        String path = UPLOAD_DIR + fullName; // 文件路径
        // 文件上传
        File uploadFile = new File(path);
        file.transferTo(uploadFile);
        // 将文件信息存入数据库
        FileEntity fileEntity = new FileEntity();
        fileEntity.setFid(fid);
        fileEntity.setFname(fname);
        fileEntity.setType(type);
        fileEntity.setPath(path);
        fileMapper.addFile(fileEntity);
        return Result.success("文件上传成功!", fileEntity);
    }

}

4. Controller

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/uploadLicence")
    public Result uploadLicence(MultipartFile file) throws IOException {
        return fileService.uploadLicence(file);
    }

}

参考文章:SpringBoot+Vue+ElementUI实现文件上传与文件下载_spring boot + vue上传文件-CSDN博客

你可能感兴趣的:(前端,后端,vue.js,spring,boot,javascript,elementui)