java 文件上传工具类

文件通过工具类上传到指定地址,返回文件上传后的地址
创建表
DROP TABLE IF EXISTS `upload_tool`;
CREATE TABLE `upload_tool`  (
  `id` char(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'id',
  `file_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '文件名',
  `file_url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '文件路径',
  `create_time` datetime(0) DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '上传记录表' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
FileUtils 工具类
public class FileUtils {
     //图片存储路径
     private static final String FTP_BASEPATH = "F:/yijia/";
     private static final String DATA_PATH = "F:/yijia/";
//     private static final String FTP_BASEPATH = "E:\\Workspace\\IDEA-workspace\\House_Project\\src\\main\\resources\\static\\images\\";


    //格式化时间
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    /**
     *
     * @param file 文件
     * @param fileName 原文件名
     * @return
     */
    public static String upload(MultipartFile file, String fileName){

        //按时间每天分开存储
        String timePath = sdf.format(new Date());

        //生成新的文件名称
        fileName = getFileName(fileName);

        // 生成新的文件名
        String realPath = FTP_BASEPATH + "/" + timePath + File.separator + fileName;

        //使用原文件名
        // String realPath = path + "/" + fileName;

        File dest = new File(realPath);

        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            file.transferTo(dest);
            String path = DATA_PATH + timePath +"/"+ fileName;
            return path;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            e.printStackTrace();
            return "false";
        }

    }

    /**
     * 删除图片
     * @param fileName
     * @return
     */
    public static boolean delFile(String fileName) {
        //根据图片路径获取文件对象
        File file = new File(fileName);

        //判断文件是否存在
        boolean falg = file.exists();

        if (falg){
            //存在则删除图片
            falg = file.delete();
            if (falg){
                return true;
            }else {
                log.info("***delFile falg*** 图片删除失败");
                return false;
            }
        }else {
            log.info("***delFile falg*** 图片不存在");
            return false;
        }
    }

    public static String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成新的文件名
     * @param fileOriginName 源文件名
     * @return
     */
    public static String getFileName(String fileOriginName){
        return ParamUtil.getUUID() + getSuffix(fileOriginName);
    }

    /**
     * 删除服务器端图片
     * @param imageUrl
     * @return
     */
    public static boolean delImage(String imageUrl){
        //判断地址开头协议
        boolean result = checkString(imageUrl);
        if (result){
            //截取路径
            String substring = imageUrl.substring(24,imageUrl.length());
            //拼接路径
            StringBuffer stringBuffer = new StringBuffer("/home/ftpuser");
            stringBuffer.append(substring);
            boolean del = delFile(stringBuffer.toString());
            return del;
        } else {
            //截取路径
            String substring = imageUrl.substring(23,imageUrl.length());
            //拼接路径
            StringBuffer stringBuffer = new StringBuffer("/home/ftpuser");
            stringBuffer.append(substring);
            boolean del = delFile(stringBuffer.toString());
            return del;
        }
    }

    /**
     * 判断图片url
     * @param url
     * @return
     */
    public static boolean checkString(String url){
        //字符串第五位是什么
        char result = url.charAt(4);
        System.out.println("charAt方法结果:"+result);
        if (result == 's'){
            return true;
        }
        return false;
    }
}

里面用到了控制台打印log插件 需要导入weblogic integration 插件

dao层
public interface UploadToolMapper {
    int deleteByPrimaryKey(String id);

    int insert(UploadTool record);

    int insertSelective(UploadTool record);

    UploadTool selectByPrimaryKey(String id);

    int delete(String fileUrl);
}
xml 配置试sql



  
    
    
    
    
  
  
    id, file_name, file_url, create_time
  
  
  
    delete from upload_tool
    where id = #{id,jdbcType=CHAR}
  
  
    insert into upload_tool (id, file_name, file_url, 
      create_time)
    values (#{id,jdbcType=CHAR}, #{fileName,jdbcType=VARCHAR}, #{fileUrl,jdbcType=VARCHAR}, 
      #{createTime,jdbcType=TIMESTAMP})
  
  
    insert into upload_tool
    
      
        id,
      
      
        file_name,
      
      
        file_url,
      
      
        create_time,
      
    
    
      
        #{id,jdbcType=CHAR},
      
      
        #{fileName,jdbcType=VARCHAR},
      
      
        #{fileUrl,jdbcType=VARCHAR},
      
      
        #{createTime,jdbcType=TIMESTAMP},
      
    
  
  
    DELETE
    FROM upload_tool
    WHERE file_url = #{fileUrl,jdbcType=VARCHAR}
  

service层
public interface UploadService {

    Integer upload(UploadTool uploadTool);

    Integer delete(String imageUrl);


}
@Service
public class UploadServiceImpl implements UploadService {

    @Resource
    UploadToolMapper uploadToolMapper;

    /**
     * 插入上传文件信息
     * @param uploadTool
     * @return
     */
    @Override
    public Integer upload(UploadTool uploadTool) {
        Integer count = uploadToolMapper.insertSelective(uploadTool);
        if (count == 0){
            return 0;
        }
        return 1;
    }

    /**
     * 删除上传记录
     * @param imageUrl
     * @return
     */
    @Override
    public Integer delete(String imageUrl) {
        Integer count = uploadToolMapper.delete(imageUrl);
        if (count == 0){
            return 0;
        }
        return 1;
    }
}
entity层
public class UploadTool {
    private String id;

    private String fileName;

    private String fileUrl;

    private Date createTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}
controller层
@Slf4j
@Controller
@ResponseBody
@RequestMapping(value = "/FileApi")
@Api(value = "文件上传接口")
public class FileController {

    @Autowired
    UploadService uploadService;

    /**
     * 文件上传
     *
     * @param request
     * @param files
     * @return
     */
    @ApiOperation(value = "post",notes = "文件上传")
    @ApiImplicitParam(name = "file",value = "图片格式为jpg,png",required = true,paramType ="form" )
    @PostMapping(value = "/uploadFile")
    @ResponseBody
    public Object uploadMusicFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        log.info("进入上传...");
        log.info("***文件数量***:" + files.length);
        if (files.length == 0) {
            return "文件不能为空";
        }
        log.info("***文件名***:" + files[0].getOriginalFilename());
        //文件路径
        String path = "";
        //文件名后缀
        String suffix = "";
        if (files != null) {
            //返回路径集合
            List list = new ArrayList<>();
            for (MultipartFile multipartFile : files) {
                //参数封装
                UploadTool uploadTool = new UploadTool();
                uploadTool.setId(ParamUtil.getUUID());
                String fileName = multipartFile.getOriginalFilename();
                log.info("****fileName****:" + fileName);
                suffix = getFileType(fileName);
                log.info("***文件后缀***:" + suffix);
                //判断是否有文件
                if (StringUtils.isNoneBlank(fileName)) {
                    //重新生成新的文件名称
                    fileName = ParamUtil.getUUID() + suffix;
                    log.info("uploadMusicFile newName :" + fileName);
                    String resultPath = FileUtils.upload(multipartFile, fileName);
                    if ("false".equals(resultPath)) {
                        return "文件上传失败";
                    } else {
                        log.info("文件上传成功!");
                        path = resultPath;
                        log.info("上传成功:" + path);
                        list.add(path);
                    }
                    //文件名称
                    uploadTool.setFileName(fileName);
                    //文件存放路径
                    uploadTool.setFileUrl(resultPath);
                    //创建时间
                    uploadTool.setCreateTime(new Date());
                    //插入记录
                    uploadService.upload(uploadTool);
                }
                log.info("****upload:****" + uploadTool.toString());
            }
            log.info("result:" + path);
            return new CommonResult().success("图片上传成功",path);
        }
        return new CommonResult().failed("文件上传失败");
    }

    /**
     * 删除服务器图片
     *
     * @param request
     * @return
     */

    @RequestMapping(value = "/delImage")
    @ResponseBody
    public Object delImage(HttpServletRequest request) {
        log.info("***删除图片地址***:" + request.getParameter("imageUrl"));
        //获取地址
        String imageUrl = request.getParameter("imageUrl");
        //判断地址开头协议
        boolean result = FileUtils.checkString(imageUrl);
        if (result) {
            //截取路径
            String substring = imageUrl.substring(21);
            log.info("***删除图片地址***截取部分:" + substring);
            //拼接路径
            StringBuffer stringBuffer = new StringBuffer("/home/ftpuser");
            stringBuffer.append(substring);
            log.info("***删除图片地址***拼接路径:" + stringBuffer.toString());
            boolean del = FileUtils.delFile(stringBuffer.toString());
            if (del) {
                Integer count = uploadService.delete(imageUrl);
                log.info("***https删除图片***:" + count);
                return new CommonResult().success("图片删除成功");
            } else {
                return new CommonResult().failed("图片删除失败");
            }
        } else {
            //截取路径
            String substring = imageUrl.substring(21);
            log.info("***删除图片地址***截取部分:" + substring);
            //拼接路径
            StringBuffer stringBuffer = new StringBuffer("/home/ftpuser");
            stringBuffer.append(substring);
            log.info("***删除图片地址***拼接路径:" + stringBuffer.toString());
            boolean del = FileUtils.delFile(stringBuffer.toString());
            if (del) {
                Integer count = uploadService.delete(imageUrl);
                log.info("***http删除图片***:" + count);
                return new CommonResult().success("图片删除成功");
            } else {
                return new CommonResult().failed("图片删除失败");
            }
        }
    }

    /**
     * 判断文件
     *
     * @param filename
     * @return
     */
    public static String getFileType(String filename) {
        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
            return ".jpg";
        } else if (filename.endsWith(".png") || filename.endsWith(".PNG")) {
            return ".png";
        } else {
            return "application/octet-stream";
        }
    }
}

一个相对完整的实现文件上传的接口搞定

你可能感兴趣的:(java 文件上传工具类)