赞
踩
在一些web应用项目实施过程,会碰到这么一个问题,例如:项目中有功能需要上传图片、文件等附件,这些附件在存储时常规的情况下是存储在一个固定的目录下,在部署多个相同的Tomcat实例集群的时候,往往需要考虑这些附件的同步问题,因此采用 FastDFS来对附件进行存储管理。
FastDFS 是一个开源的分布式文件系统,她对文件进行管理,功能包括:文件存储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。FastDFS的工作原理以及相关安装流程就不做过多赘述,可以搜索相关资料了解,下面就来给大家介绍一下Java如何实现通过FastDFS上传、下载、删除附件。
首先需要在项目中导入FastDFS依赖相关的Jar包,我们使用maven的情况下,如下配置:
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.6</version>
- </dependency>
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </dependency>
- <dependency>
- <groupId>org.csource</groupId>
- <artifactId>fastdfs-client-java</artifactId>
- <version>1.29-SNAPSHOT</version>
- </dependency>
第二步,在springboot项目中创建配置文件fdfs_client.conf
- #默认值为30s
- connect_timeout = 10
- #默认值为30s
- network_timeout = 30
- charset = UTF-8
- http.tracker_http_port = 8080
- # token 防盗链功能
- http.anti_steal_token = true
- #防盗链key
- http.secret_key = ZFnWLBqrX3
- #服务器
- tracker_server = 127.0.0.1:22122
第三步,创建一个实体类,定义附件相关的对象
- public class FastDFSFile {
-
- private String name;//文件名
- private byte[] content; //文件的内容,字节数组
- private String ext; //文件扩展名,不包含(.)
- private String md5; //加密
-
- public FastDFSFile() {
- }
-
- public FastDFSFile(String name, byte[] content, String ext) {
- this.name = name;
- this.content = content;
- this.ext = ext;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public byte[] getContent() {
- return content;
- }
-
- public void setContent(byte[] content) {
- this.content = content;
- }
-
- public String getExt() {
- return ext;
- }
-
- public void setExt(String ext) {
- this.ext = ext;
- }
-
- public String getMd5() {
- return md5;
- }
-
- public void setMd5(String md5) {
- this.md5 = md5;
- }
-
- public String getAuthor() {
- return author;
- }
-
- public void setAuthor(String author) {
- this.author = author;
- }
- }
第四步,创建工具类,写入相关方法
- public class FastDFSClient {
-
- private final static Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
-
- //初始化
- static {
- try {
- String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
- IniFileReader iniReader = new IniFileReader(filePath);
- String[] szTrackerServers = iniReader.getValues("tracker_server");
- ClientGlobal.init(filePath);
- } catch (Exception e) {
- throw new MyException(ResultEnum.FAST_DFS_ERROR);
- }
- }
-
- //上传
- public static String upload(FastDFSFile file){
- NameValuePair[] meta_list = new NameValuePair[1];
- meta_list[0] = new NameValuePair("author", file.getAuthor());
- long startTime = System.currentTimeMillis();
- String[] uploadResults = null;
- StorageClient storageClient=null;
- try {
- storageClient = getTrackerClient();
- //upload_file()三个参数:@param fileContent ①:文件的内容,字节数组 ②:文件扩展名 ③文件扩展信息 数组
- uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
- }catch (Exception e){
- e.printStackTrace();
- throw new MyException(ResultEnum.FAST_DFS_ERROR);
- }
- if (uploadResults == null && storageClient!=null) {
- logger.error("upload file fail, error code:" + storageClient.getErrorCode());
- }
- logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
- String groupName = uploadResults[0];
- String remoteFileName = uploadResults[1];
- return groupName+"/"+remoteFileName;
- }
-
- //下载文件
- public static boolean downloadFile(String localFilename, String groupName, String remoteFilename) {
- //localFilename 本地文件名
- //groupName 文件在FastDFS中的组名
- //remoteFilename 文件在FastDFS中的名称
- File file = new File(localFilename);
- if(!file.exists()) {
- if(!file.getParentFile().exists()){
- file.getParentFile().mkdirs();
- }
- try {
- file.createNewFile();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }else if(file.length()>0){
- logger.info("file.length()="+file.length());
- return true;
- }
- TrackerServer trackerServer;
- TrackerClient trackerClient=new TrackerClient();
- StorageServer storageServer=null;
- StorageClient storageClient=null;
- try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
- trackerServer = trackerClient.getTrackerServer();
- storageServer=trackerClient.getStoreStorage(trackerServer);
- storageClient= new StorageClient(trackerServer, storageServer);
- byte[] content = storageClient.download_file(groupName, remoteFilename);
- if (content == null || content.length == 0) {
- boolean flag = file.delete();
- return false;
- }
- bos.write(content);
- return true;
- } catch (IOException | MyException e) {
- e.printStackTrace();
- return false;
- }catch (Exception e){
- e.printStackTrace();
- return false;
- }
- }
-
- //删除
- public static int deleteFile(String groupName, String remoteFileName) throws Exception {
- //remoteFileName--文件路径 例如:M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
- //groupName --文件路径,例如:group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg中的group1
- StorageClient storageClient = getTrackerClient();
- return storageClient.delete_file(groupName, remoteFileName);
- }
-
- //查询文件信息
- public static FileInfo getFile(String groupName, String remoteFileName) {
- try {
- StorageClient storageClient = getTrackerClient();
- return storageClient.get_file_info(groupName, remoteFileName);
- } catch (IOException e) {
- logger.error("IO Exception: Get File from Fast DFS failed", e);
- } catch (Exception e) {
- logger.error("Non IO Exception: Get File from Fast DFS failed", e);
- }
- return null;
- }
- }
第五步,调用示例
- public class UploadDFS {
-
- //上传文件
- public static String saveFile(MultipartFile multipartFile) throws IOException {
- String fileName=multipartFile.getOriginalFilename();
- String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
- byte[] file_buff = null;
- InputStream inputStream=multipartFile.getInputStream();
- if(inputStream!=null){
- int len1 = inputStream.available();
- file_buff = new byte[len1];
- inputStream.read(file_buff);
- }
- inputStream.close();
- FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
- return FastDFSClient.upload(file);
- }
-
- //下载
- public static boolean downFile(String localFilename, String groupName, String remoteFilename){
- //下载完成后到存储路径找下载的文件 localFilename
- return FastDFSClient.downloadFile(localFilename,groupName,remoteFilename);
- }
-
-
- //删除
- public static void deleteFile(String groupName, String remoteFileName){
- try {
- int res= FastDFSClient.deleteFile(groupName,remoteFileName);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。