张晓波
2023-09-19 164694c47c35d6654df69b533e8dbf8b5423efc5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package com.thhy.filectrl.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.utils.StringUtils;
import com.thhy.filectrl.service.FdfsService;
import com.thhy.filectrl.utils.ConvertUtil;
import com.thhy.general.common.BasicStatus;
import com.thhy.general.exception.BasicException;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import static com.thhy.general.common.BasicStatus.FILE_NOT_EXISTS_REMOTE;
import static com.thhy.general.common.BasicStatus.FILE_UPLOAD_ERROR;
 
@Service
//@ConditionalOnProperty(prefix = "fastdfs",name = "enbale",havingValue = "true")
public class FdfsServiceImpl implements FdfsService {
 
    private Logger logger = LoggerFactory.getLogger(FdfsServiceImpl.class);
 
    @Autowired
    private StorageClient storageClient;
 
    @Value("${file.workspace}")
    private String workspace;
 
 
    public String upload(MultipartFile file) {
        try {
            //设置文件信息
            NameValuePair[] nv = new NameValuePair[2];
            nv[0] = new NameValuePair("name",file.getOriginalFilename());
            nv[1] = new NameValuePair("uploadTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            String[] paths = storageClient.upload_file(file.getBytes(), FilenameUtils.getExtension(file.getOriginalFilename()),nv);
            return paths[0]+"/"+paths[1];
        }catch (Exception exception){
            throw new BasicException(FILE_UPLOAD_ERROR,exception);
        }
    }
 
    @Override
    public void downfile(String dfsPath,String fileName, HttpServletResponse resp) {
        //storageClient.download_file()
        String groupName = dfsPath.substring(0,dfsPath.indexOf("/"));
        String remoteFile = dfsPath.substring(dfsPath.indexOf("/")+1,dfsPath.length());
        resp.setCharacterEncoding("utf-8");
        try {
            if(StringUtils.isBlank(fileName)){
                NameValuePair[] nv = storageClient.get_metadata(groupName,remoteFile);
                for(NameValuePair n : nv){
                    if("name".equals(n.getName())){
                        fileName = n.getValue();
                        break;
                    }
                }
            }
            fileName = URLEncoder.encode(fileName,"UTF-8");
            resp.setHeader("Content-Disposition","attachment;filename="+fileName);
            byte[] bytes = storageClient.download_file(groupName,remoteFile);
            OutputStream os = resp.getOutputStream();
            os.write(bytes);
        } catch (IOException e) {
            throw new BasicException(FILE_NOT_EXISTS_REMOTE);
        } catch (MyException e) {
            throw new RuntimeException(e);
        }
 
    }
 
    @Override
    public void preview(String dfsPath,HttpServletResponse resp) {
        String groupName = dfsPath.substring(0,dfsPath.indexOf("/"));
        String remoteFile = dfsPath.substring(dfsPath.indexOf("/")+1,dfsPath.length());
        resp.setCharacterEncoding("utf-8");
 
        OutputStream os = null;
        InputStream inputStream = null;
        try {
            String fileName = dfsPath.substring(dfsPath.lastIndexOf("/")+1,dfsPath.lastIndexOf("."));
            String extendName = dfsPath.substring(dfsPath.lastIndexOf(".")+1,dfsPath.length());
            if("pdf".equals(extendName)||"PDF".equals(extendName)){
                downfile(dfsPath,"preview"+extendName,resp);
                return;
            }
            fileName = URLEncoder.encode(fileName,"UTF-8");
            resp.setHeader("Content-Disposition","attachment;filename="+fileName+".pdf");
            byte[] bytes = storageClient.download_file(groupName,remoteFile);
 
            FileOutputStream fos = new FileOutputStream(new File(workspace+"/"+fileName+"."+extendName));
            fos.write(bytes);
            fos.close();
            logger.info("文件保存本地成功:"+workspace+"/"+fileName+"."+extendName);
 
            ConvertUtil.executeCommand(workspace,fileName+"."+extendName);
            File file = new File(workspace+"/"+fileName+".pdf");
            logger.info("命令执行完成,pdf是否存在了"+file.exists());
            inputStream = new FileInputStream(file);
 
            byte[] bytes1 = new byte[inputStream.available()];
            inputStream.read(bytes1);
            logger.info("读取PDF成功");
            os = resp.getOutputStream();
            os.write(bytes1);
        } catch (IOException e) {
            throw new BasicException(FILE_NOT_EXISTS_REMOTE);
        } catch (MyException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(inputStream!=null)inputStream.close();
                if(os!=null)os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
 
        }
    }
 
    @Override
    public NameValuePair[] fileInfo(String fullPath) {
        String groupName = fullPath.substring(0,fullPath.indexOf("/"));
        String remoteFile = fullPath.substring(fullPath.indexOf("/")+1,fullPath.length());
        try {
            NameValuePair[] nv = storageClient.get_metadata(groupName,remoteFile);
            return nv;
        } catch (IOException e) {
            throw new BasicException(BasicStatus.FILE_PATH_ERROR);
        } catch (MyException e) {
            throw new RuntimeException(e);
        }
    }
 
    public static void main(String[] args) {
        String dfsPath = "group1/M00/00/00/bx5d1GRGObqAYmLZAAoS1mNy1B8114.png";
        String groupName = dfsPath.substring(0,dfsPath.indexOf("/"));
        String remoteFile = dfsPath.substring(dfsPath.indexOf("/")+1,dfsPath.length());
        String fileName = dfsPath.substring(dfsPath.lastIndexOf("/")+1,dfsPath.lastIndexOf("."));
        String extendName = dfsPath.substring(dfsPath.lastIndexOf(".")+1,dfsPath.length());
        System.out.printf(fileName);
    }
 
 
}