SpringBoot整合fastdfs


1、导入jar包

<dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.5</version>
        </dependency>

2、配置类

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
 
/**
 * 
 */
@Configuration
@Import(FdfsClientConfig.class) // 导入FastDFS-Client组件
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) // 解决jmx重复注册bean的问题
public class FdfsConfiguration {
}
server:
  port: 80
 
 
 
# 分布式文件系统FDFS配置
fdfs:
  soTimeout: 1500 #socket连接超时时长
  connectTimeout: 600 #连接tracker服务器超时时长
  reqHost: 192.168.8.101   #nginx访问地址
  reqPort: 80              #nginx访问端口
  thumbImage: #缩略图生成参数,可选
      width: 150
      height: 150
  trackerList: #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port
      - 192.168.8.101:22122
      - 192.168.8.102:22122
      
spring:
  application:
    name: FastDFS-Test
  servlet:
    multipart:
      max-file-size: 100MB # 最大支持文件大小
      max-request-size: 100MB # 最大支持请求大小
  mvc:
    view:
      prefix: /WEB-INF/
      suffix: .jsp



3、工具类

 
import java.io.IOException;
import java.io.InputStream;
 
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
 
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
 
 
@Component
public class FastDFSClientUtil {
 
	@Value("${fdfs.reqHost}")
    private String reqHost;
 
    @Value("${fdfs.reqPort}")
    private String reqPort;
	
    @Autowired
    private FastFileStorageClient storageClient;
    
    @Autowired
    private ThumbImageConfig thumbImageConfig; //创建缩略图   , 缩略图访问有问题,暂未解决
 
     
   public String uploadFile(MultipartFile file) throws IOException {
       StorePath storePath = storageClient.uploadFile((InputStream)file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
       
       String path = thumbImageConfig.getThumbImagePath(storePath.getPath()) ;
       System.out.println("thumbImage :" + path);  //   缩略图访问有问题,暂未解决
       
       return getResAccessUrl(storePath);
   }
 
   public void delFile(String groupName , String path) {
	   storageClient.deleteFile(filePath);
   }
   
   public InputStream download(String groupName, String path ) {
	   InputStream ins =  storageClient.downloadFile(groupName, path, new DownloadCallback<InputStream>(){
		@Override
		public InputStream recv(InputStream ins) throws IOException {
			// 将此ins返回给上面的ins 
			return ins;
		}}) ;
	   return ins ;
   }
   
    /**
      * 封装文件完整URL地址
     * @param storePath
     * @return
     */
   private String getResAccessUrl(StorePath storePath) {
       String fileUrl = "http://" + reqHost + ":" + reqPort + "/" + storePath.getFullPath();
       return fileUrl;
   }
}



4、编写controller

 
import java.io.IOException;
import java.io.InputStream;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
@Controller
public class UploadController {
 
	@Autowired
	private FastDFSClientUtil dfsClient;
 
	@RequestMapping("/")
	public String index() {
		return "index";
	}
 
	@PostMapping("/upload")
	public String fdfsUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
 
		try {
			String fileUrl = dfsClient.uploadFile(file);
			request.setAttribute("msg", "成功上传文件,  '" + fileUrl + "'");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "index";
	}
 
	
	/*
	 * http://localhost/download?filePath=group1/M00/00/00/wKgIZVzZEF2ATP08ABC9j8AnNSs744.jpg
	 */
	@RequestMapping("/download")
	public void download(String filePath ,HttpServletRequest request ,HttpServletResponse response) throws IOException {
		
		//    group1/M00/00/00/wKgIZVzZEF2ATP08ABC9j8AnNSs744.jpg
		String[] paths = filePath.split("/");
		String groupName = null ;
		for (String item : paths) {
			if (item.indexOf("group") != -1) {
				groupName = item;
				break ;
			}
		}
		String path = filePath.substring(filePath.indexOf(groupName) + groupName.length() + 1, filePath.length());
		InputStream input = dfsClient.download(groupName, path);
		
        //根据文件名获取 MIME 类型
		String fileName = paths[paths.length-1] ;
		System.out.println("fileName :" + fileName); // wKgIZVzZEF2ATP08ABC9j8AnNSs744.jpg
        String contentType = request.getServletContext().getMimeType(fileName);
        String contentDisposition = "attachment;filename=" + fileName;
        
        // 设置头
        response.setHeader("Content-Type",contentType);
        response.setHeader("Content-Disposition",contentDisposition);
 
        // 获取绑定了客户端的流
        ServletOutputStream output = response.getOutputStream();
 
        // 把输入流中的数据写入到输出流中
        IOUtils.copy(input,output);
        input.close();
		
	}
	
	/**
	 * http://localhost/deleteFile?filePath=group1/M00/00/00/wKgIZVzZaRiAZemtAARpYjHP9j4930.jpg
	 * @param fileName  group1/M00/00/00/wKgIZVzZaRiAZemtAARpYjHP9j4930.jpg
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteFile")
	public String delFile(String filePath , HttpServletRequest request ,HttpServletResponse response)  {
		
		try {
			dfsClient.delFile(filePath); 
		} catch(Exception e) { 
			// 文件不存在报异常 : com.github.tobato.fastdfs.exception.FdfsServerException: 错误码:2,错误信息:找不到节点或文件
			// e.printStackTrace();
		}
		request.setAttribute("msg", "成功删除,'" + filePath);
		
		return "index";
	}
	
 
}


5、jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath() ;
	%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FastDFS-Demo</title>
</head>
<body>
 
${msg }
<br>
<form action="<%=path%>/upload" method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="submit" value="提交">
</form>
 
</body>
</html>





fastdfs springboot

2020.11.18 21:24

https://www.meihaocloud.com.com/125.html , 欢迎转载,请在文章页标出原文连接 !


Copyright © 2020 千夕网 联系站长

粤公网安备 44030302001408号 粤ICP备19099833号-1