文件上传保存两次

113 阅读1分钟
@RequestMapping("upload")
public String uploadFile(MultipartFile multipartFile, String dir) {
    try {
        if (multipartFile.isEmpty()) {
            return "请选择文件";
        }
        // 获取文件的名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件后缀 例如:.png
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // uuid 生成文件名
        String uuid = String.valueOf(UUID.randomUUID());
        // 根路径,在 resources/static/upload
        String basePath = ResourceUtils.getURL("classpath:").getPath() + "static/upload/" + (StringUtils.isNotBlank(dir) ? (dir + "/") : "");
        // 新的文件名,使用uuid生成文件名
        String fileName = uuid + fileSuffix;
        // 创建新的文件
        File fileExist = new File(basePath);
        // 文件夹不存在,则新建
        if (!fileExist.exists()) {
            fileExist.mkdirs();
        }
        // 获取文件对象
        File file = new File(basePath, fileName);
        String path = "src/main/resources/static/upload";
        File copyFile = new File(path);
        // 不存在,则创建该文件夹
        if(!copyFile.exists()){
            copyFile.mkdirs();
        }
        String copyPath = copyFile.getCanonicalPath()+"/"+fileName;
        File newFile = new File(copyPath);

        //Springboot中直接用transferTo会报找不到路径的错,得复制一份才行
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),newFile);

        // 完成文件的上传
        multipartFile.transferTo(file);
        // 返回绝对路径
        return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + 8888 + "/upload/" + fileName;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "上传失败";
}