fastDFS文件上传服务

fastDFS文件上传 方便大家 也给自己记个记录
1.新建文件实体对象

/**
 * FastDFS文件实体类
 */
@ApiModel(value = "FastDFSFile", description = "FastDFS文件实体")
public class FastDFSFile {
    @ApiModelProperty(name = "id", value = "主键Id")
    private String id;
    //返回的文件Id
    @ApiModelProperty(name = "fileId", value = "文件Id")
    private String fileId;
    //文件请求路径
    @ApiModelProperty(name = "filePath", value = "文件请求路径")
    private String filePath;
    //文件大小
    @ApiModelProperty(name = "fileSize", value = "文件大小")
    private long fileSize;
    //文件名称
    @ApiModelProperty(name = "fileName", value = "文件名称")
    private String fileName;
    //文件类型
    @ApiModelProperty(name = "fileType", value = "文件类型")
    private String fileType;
    //图片宽度
    @ApiModelProperty(name = "fileWidth", value = "图片宽度")
    private int fileWidth;
    //图片高度
    @ApiModelProperty(name = "fileHeight", value = "图片高度")
    private int fileHeight;
    //用户名称,用于授权暂时不用
    @ApiModelProperty(name = "userName", value = "用户名称")
    private String userName;
    //业务key
    @ApiModelProperty(name = "businessKey", value = "业务key")
    private String businessKey;
    //业务标签
    @ApiModelProperty(name = "fileTag", value = "业务标签")
    private String fileTag;
    @ApiModelProperty(name = "metadata", value = "文件元信息")
    private String metaData;

2.新建文件上传控制器

public class FileController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    /**
     * 上传单个文件
     * @param request
     * @param file
     * @param fileTag
     * @param businessKey
     * @param metaData
     * @return
     */
    @PostMapping("/uploadSingle")
    @ApiOperation(value = "上传单个文件")
    public SwaggerResultUtil<FastDFSFile> uploadSingle(HttpServletRequest request,
         @RequestParam("file") MultipartFile file,
         @RequestParam(value = "fileTag", required = false) String fileTag,
         @RequestParam(value = "businessKey", required = false) String businessKey,
         @RequestParam(value = "meteData", required = false) String metaData) {
        SwaggerResultUtil<FastDFSFile> swaggerResultUtil = new SwaggerResultUtil<>();
        try{
            String userName = UserInfoUtil.getUserName(request);
            if(file == null){
                swaggerResultUtil.setCode(Global.PARAM_ERROR);
                swaggerResultUtil.setMsg("请上传文件");
            }else{
                FastDFSFile fastDFSFile = fileService.uploadSingle(file, fileTag, businessKey, metaData,userName);
                if(fastDFSFile != null){
                    swaggerResultUtil.setCode(Global.SUCCESS);
                    swaggerResultUtil.setMsg("文件上传成功");
                    swaggerResultUtil.setData(fastDFSFile);
                }else{
                    swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
                    swaggerResultUtil.setMsg("文件上传失败");
                }
            }
        }catch(Exception e) {
            swaggerResultUtil.setDefError(e);
            swaggerResultUtil.setMsg("文件上传失败");
            swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
            LOGGER.error(e.getMessage(), e);
        }
        return swaggerResultUtil;
    }

    /**
     * 查询文件
     * @param fileId
     * @return
     */
    @GetMapping("/query")
    @ApiOperation(value = "查询文件")
    public SwaggerResultUtil<FastDFSFile> query(@RequestParam("fileId") String fileId) {
        SwaggerResultUtil<FastDFSFile> swaggerResultUtil = new SwaggerResultUtil<>();
        try{
            if(fileId == null || "".equals(fileId)){
                swaggerResultUtil.setCode(Global.PARAM_ERROR);
                swaggerResultUtil.setMsg("参数错误");
            }else{
                FastDFSFile fastDFSFile = fileService.query(fileId);
                if(fastDFSFile != null){
                    swaggerResultUtil.setCode(Global.SUCCESS);
                    swaggerResultUtil.setMsg("文件查询成功");
                    swaggerResultUtil.setData(fastDFSFile);
                }else{
                    swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
                    swaggerResultUtil.setMsg("文件查询失败");
                }
            }
        }catch(Exception e) {
            swaggerResultUtil.setDefError(e);
            swaggerResultUtil.setMsg("文件查询失败");
            swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
            LOGGER.error(e.getMessage(), e);
        }
        return swaggerResultUtil;
    }

    /**
     * 删除单个文件
     * @param fileId
     * @return
     */
    @DeleteMapping("/deleteSingle")
    @ApiOperation(value = "删除单个文件")
    public SwaggerResultUtil<Integer> deleteSingle(@RequestParam("fileId") String fileId) {
        SwaggerResultUtil<Integer> swaggerResultUtil = new SwaggerResultUtil<>();
        try{
            if(fileId == null || "".equals(fileId)){
                swaggerResultUtil.setCode(Global.PARAM_ERROR);
                swaggerResultUtil.setMsg("参数错误");
            }else{
                Integer num = fileService.deleteSingle(fileId);
                if(num > 0){
                    swaggerResultUtil.setCode(Global.SUCCESS);
                    swaggerResultUtil.setMsg("文件删除成功");
                    swaggerResultUtil.setData(num);
                }else{
                    swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
                    swaggerResultUtil.setMsg("文件删除失败");
                }
            }
        }catch(Exception e) {
            swaggerResultUtil.setDefError(e);
            swaggerResultUtil.setMsg("文件删除失败");
            swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
            LOGGER.error(e.getMessage(), e);
        }
        return swaggerResultUtil;
    }

    /**
     * 批量上传文件
     * @param request
     * @param files
     * @param fileTag
     * @param businessKey
     * @param metaData
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "批量上传文件")
    public SwaggerResultUtil<List<FastDFSFile>> upload(HttpServletRequest request,
         @RequestParam("files") MultipartFile[] files,
         @RequestParam(value = "fileTag", required = false) String fileTag,
         @RequestParam(value = "businessKey", required = false) String businessKey,
         @RequestParam(value = "meteData", required = false) String metaData) {
        SwaggerResultUtil<List<FastDFSFile>> swaggerResultUtil = new SwaggerResultUtil<>();
        try{
            String userName = UserInfoUtil.getUserName(request);
            if(files == null){
                swaggerResultUtil.setCode(Global.PARAM_ERROR);
                swaggerResultUtil.setMsg("请上传文件");
            }else{
                List<FastDFSFile> fastDFSFileList = fileService.upload(files, fileTag, businessKey, metaData,userName);
                if(fastDFSFileList != null && fastDFSFileList.size() > 0){
                    swaggerResultUtil.setCode(Global.SUCCESS);
                    swaggerResultUtil.setMsg("文件批量上传成功");
                    swaggerResultUtil.setData(fastDFSFileList);
                }else{
                    swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
                    swaggerResultUtil.setMsg("文件批量上传失败");
                }
            }
        }catch(Exception e) {
            swaggerResultUtil.setDefError(e);
            swaggerResultUtil.setMsg("文件批量上传失败");
            swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
            LOGGER.error(e.getMessage(), e);
        }
        return swaggerResultUtil;
    }

    /**
     * 批量删除文件
     * @param fileIds
     * @return
     */
    @DeleteMapping("/delete")
    @ApiOperation(value = "批量删除文件")
    public SwaggerResultUtil<Integer> delete(@RequestParam("fileIds") List<String> fileIds) {
        SwaggerResultUtil<Integer> swaggerResultUtil = new SwaggerResultUtil<>();
        try{
            if(fileIds == null){
                swaggerResultUtil.setCode(Global.PARAM_ERROR);
                swaggerResultUtil.setMsg("参数错误");
            }else{
                Integer num = fileService.delete(fileIds);
                if(num > 0){
                    swaggerResultUtil.setCode(Global.SUCCESS);
                    swaggerResultUtil.setMsg("文件批量删除成功");
                    swaggerResultUtil.setData(num);
                }else{
                    swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
                    swaggerResultUtil.setMsg("文件批量删除失败");
                }
            }
        }catch(Exception e) {
            swaggerResultUtil.setDefError(e);
            swaggerResultUtil.setMsg("文件批量删除失败");
            swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
            LOGGER.error(e.getMessage(), e);
        }
        return swaggerResultUtil;
    }

    /**
     * 下载单个文件
     * @param fileId
     * @return
     */
    @GetMapping("/downLoadSingle")
    @ApiOperation(value = "下载单个文件")
    public SwaggerResultUtil<String> downLoadSingle(@RequestParam("fileId") String fileId) {
        SwaggerResultUtil<String> swaggerResultUtil = new SwaggerResultUtil<>();
        try{
            if(fileId == null || "".equals(fileId)){
                swaggerResultUtil.setCode(Global.PARAM_ERROR);
                swaggerResultUtil.setMsg("参数错误");
            }else{
                byte[] bytes = fileService.downLoadSingle(fileId);
                FastDFSFile file = fileService.query(fileId);
                if(bytes != null && bytes.length > 0){
                    swaggerResultUtil.setCode(Global.SUCCESS);
                    swaggerResultUtil.setMsg("文件下载成功");
                    FileUtils.writeByteArrayToFile(new File("D:\\"+file.getFileName()),bytes);
                }else{
                    swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
                    swaggerResultUtil.setMsg("文件下载失败");
                }
            }
        }catch(Exception e) {
            swaggerResultUtil.setDefError(e);
            swaggerResultUtil.setMsg("文件下载失败");
            swaggerResultUtil.setCode(Global.INTERNAL_SERVER_ERROR);
            LOGGER.error(e.getMessage(), e);
        }
        return swaggerResultUtil;
    }



3.文件上传service

public interface FileService {
    /**
     * 上传单个文件
     * @param multipartFile 文件
     * @param fileTag 文件标签
     * @param businessKey 业务key
     * @param metaData 元信息,json格式
     * @param userName 上传人
     * @return
     */
    public FastDFSFile uploadSingle(MultipartFile multipartFile, String fileTag, String businessKey, String metaData,String userName);

    /**
     * 批量上传文件
     * @param multipartFiles
     * @param fileTag
     * @param businessKey
     * @param metaData
     * @param userName
     * @return
     */
    public List<FastDFSFile> upload(MultipartFile[] multipartFiles, String fileTag, String businessKey, String metaData, String userName);

    /**
     * 根据文件Id查询文件详情
     * @param fileId
     * @return
     */
    FastDFSFile query(String fileId);

    /**
     * 根据文件Id删除文件
     * @param fileId
     * @return
     */
    Integer deleteSingle(String fileId) throws IOException;

    /**
     * 批量删除文件
     * @param fileIds
     * @return
     */
    Integer delete(List<String> fileIds) throws IOException;

    /**
     * 下载单个文件
     * @param fileId
     * @return
     * @throws IOException
     */
    byte[] downLoadSingle(String fileId) throws IOException, MyException;

}

4.文件上传实现类

public class FileServiceImpl implements FileService {  // 服务器地址自行配置
//    @Value("${file_server_url}")
//    String file_server_url;
    @Value("${fastdfs.tracker_servers}")
    String tracker_servers;
	/*@Value("${fastdfs.connect_timeout_in_seconds}")
	int connect_timeout_in_seconds;
	@Value("${fastdfs.network_timeout_in_seconds}")
	int network_timeout_in_seconds;*/
    @Value("${fastdfs.charset}")
    String charset;
    @Autowired
    private FileMapper fileMapper;

    /**
     * 上传文件
     * @param file
     * @param fileTag 文件标签
     * @param businessKey 业务key
     * @param metaData 元信息,json格式
     * @return
     */
    @Override
    public FastDFSFile uploadSingle(MultipartFile file, String fileTag, String businessKey, String metaData,String userName) {
        //上传文件到fastDFS
        String fileId = fastDFS_upload(file);
        //创建文件信息对象
        FastDFSFile fastDFSFile = new FastDFSFile();
        //文件id
        fastDFSFile.setFileId(fileId);
        //文件在文件系统中的路径
        fastDFSFile.setFilePath(fileId);
        //业务标识
        fastDFSFile.setBusinessKey(businessKey);
        //标签
        fastDFSFile.setFileTag(fileTag);
        //元数据
        fastDFSFile.setMetaData(metaData);
        if(file != null){
           //文件名称
           fastDFSFile.setFileName(file.getOriginalFilename());
           //文件大小
           fastDFSFile.setFileSize(file.getSize());
           //文件类型
           fastDFSFile.setFileType(file.getContentType());
           BufferedImage bufferedImage = null;
           try {
               bufferedImage = ImageIO.read(file.getInputStream());
               if(bufferedImage != null){
                   fastDFSFile.setFileWidth(bufferedImage.getWidth());
                   fastDFSFile.setFileHeight(bufferedImage.getHeight());
               }
           } catch (IOException e) {
                e.printStackTrace();
           }
        }
        if(userName != null){
            fastDFSFile.setUserName(userName);
        }
        fileMapper.insert(fastDFSFile);
        return fastDFSFile;
    }
    //加载fastDFS的配置
    private void initFastDFSConfig(){
        try {
            ClientGlobal.initByTrackers(tracker_servers);
			/*ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
			ClientGlobal.setG_network_timeout(network_timeout_in_seconds);*/
            ClientGlobal.setG_charset(charset);
        } catch (Exception e) {
            e.printStackTrace();
            //初始化文件系统出错
        }
    }
    //上传文件到fastDFS,返回文件id
    public String fastDFS_upload(MultipartFile file) {
        try {
            //加载fastDFS的配置
            initFastDFSConfig();
            //创建tracker client
            TrackerClient trackerClient = new TrackerClient();
            //获取trackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //获取storage
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            //创建storage client
            StorageClient1 storageClient1 = new StorageClient1(trackerServer,storeStorage);
            //上传文件
            //获取文件字节内容
            byte[] bytes = file.getBytes();
            //获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            //定义文件扩展名
            String extName = null;
            if(originalFilename != null){
                //获取文件扩展名
                extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            }
            //返回文件id
            return storageClient1.upload_file1(bytes, extName, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 根据文件Id查询文件详情
     * @param fileId
     * @return
     */
    @Override
    public FastDFSFile query(String fileId){
        return fileMapper.selectByPrimaryKey(fileId);
    }

    /**
     * 根据文件Id删除文件
     * @param fileId
     * @return
     */
    @Override
    public Integer deleteSingle(String fileId) throws IOException {
        //初始化fastDFS环境
        initFastDFSConfig();
        TrackerClient tracker = new TrackerClient();
        TrackerServer trackerServer = tracker.getConnection();
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
        //删除fastDFS文件服务器中的文件
        try {
            storageClient1.delete_file1(fileId);
        } catch (MyException e) {
            e.printStackTrace();
        }
        //删除文件服务表中的数据
        return fileMapper.deleteByPrimaryKey(fileId);
    }

    /**
     * 批量删除文件
     * @param fileIds
     * @return
     * @throws IOException
     */
    @Override
    public Integer delete(List<String> fileIds) throws IOException {
        //初始化fastDFS环境
        initFastDFSConfig();
        TrackerClient tracker = new TrackerClient();
        TrackerServer trackerServer = tracker.getConnection();
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
        //删除fastDFS文件服务器中的文件
        try {
            for (String fileId : fileIds) {
                storageClient1.delete_file1(fileId);
            }
        } catch (MyException e) {
            e.printStackTrace();
        }
        //删除文件服务表中的数据
        return fileMapper.deleteByFileIds(fileIds);
    }

    /**
     * 批量上传文件
     * @param multipartFiles
     * @param fileTag
     * @param businessKey
     * @param metaData
     * @param userName
     * @return
     */
    @Override
    public List<FastDFSFile> upload(MultipartFile[] multipartFiles, String fileTag, String businessKey, String metaData, String userName) {
        List<FastDFSFile> fastDFSFiles = new ArrayList<>();
        for (MultipartFile file : multipartFiles) {
            FastDFSFile fastDFSFile = uploadSingle(file, fileTag, businessKey, metaData, userName);
            if(fastDFSFile != null){
                fastDFSFiles.add(fastDFSFile);
            }
        }
        return fastDFSFiles;
    }

    /**
     * 下载单个文件
     * @param fileId
     * @return
     * @throws IOException
     */
    @Override
    public byte[] downLoadSingle(String fileId) throws IOException {
        //初始化fastDFS环境
        initFastDFSConfig();
        TrackerClient tracker = new TrackerClient();
        TrackerServer trackerServer = tracker.getConnection();
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
        //下载文件
        try {
            return storageClient1.download_file1(fileId);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return null;
    }
}

其他dao和mapper可以自行

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值