liusheng
14 小时以前 c62e26954e41360fc6a2efc874815aa84f8b0073
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package com.ruoyi.web.controller.common;
 
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.PhotoEnum;
import com.ruoyi.common.enums.RadioEnum;
import com.ruoyi.common.enums.VadioEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.smartor.domain.HtmlContentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
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.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
 
/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@Api(description = "通过请求处理")
@RequestMapping("/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
 
    @Autowired
    private ServerConfig serverConfig;
 
    private static final String FILE_DELIMETER = ",";
 
    @Value("${uploadSwitch}")
    private Integer uploadSwitch;
 
    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;
 
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
 
    /**
     * 分类上传请求
     */
    @ApiOperation("分类上传请求")
    @PostMapping("/uploadSort")
    public AjaxResult uploadFileSort(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String originalFilename = file.getOriginalFilename().split("\\.", 2)[1];
            if (VadioEnum.getDescByCode(originalFilename)) {
                filePath = filePath + "/vadio";
            } else if (RadioEnum.getDescByCode(originalFilename)) {
                filePath = filePath + "/radio";
            } else if (PhotoEnum.getDescByCode(originalFilename)) {
                filePath = filePath + "/photo";
            } else {
                filePath = filePath + "/file";
            }
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.uploadSort(filePath, file);
            String url = null;
            //新华医院特殊,这个视频的访问得转
            String xhPath = "http://218.108.11.22:8093/profile-api";
            if (uploadSwitch == 1) {
                String fn = fileName.replaceAll("/profile", "");
                url = xhPath + fn;
            } else {
                url = serverConfig.getUrl() + fileName;
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
 
    /**
     * 上传并转成html请求
     */
    @ApiOperation("word文件上传并转成html")
    @PostMapping("/uploadShow")
    public AjaxResult uploadFileShow(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String originalFilename = file.getOriginalFilename().split("\\.", 2)[1];
            filePath = filePath + "/show/" + file.getOriginalFilename().split("\\.", 2)[0];
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.uploadSort(filePath, file);
            //将word转成html
            convertDocToHtml(filePath + "\\" + file.getOriginalFilename(), filePath + "\\" + file.getOriginalFilename().split("\\.", 2)[0] + ".html");
 
            String url = null;
            String xhPath = "http://218.108.11.22:8093/profile-api";
            if (uploadSwitch == 1) {
                String fn = fileName.replaceAll("\\.[^.]*$", ".html").replaceAll("/profile", "");
                url = xhPath + fn;
 
            } else {
                url = serverConfig.getUrl() + fileName.replaceAll("\\.[^.]*$", ".html");
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
 
    /**
     * 通用上传请求(单个)
     */
    @ApiOperation("通用上传请求")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
 
    /**
     * 通用上传请求(多个)
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
 
    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
 
    /**
     * @param
     * @return
     */
    @ApiOperation("富文本转html")
    @PostMapping("/htmlContent")
    public AjaxResult htmlContent(@RequestBody HtmlContentVO htmlContentVO) {
        log.error("htmlContentVO入参为:{}", htmlContentVO);
        // 获取文件的原始名称
        String fileName = htmlContentVO.getFileName();
        if (!fileName.endsWith(".html")) {
            // 去掉之前的扩展名
            int lastIndex = fileName.lastIndexOf('.');
            if (lastIndex != -1) {
                fileName = fileName.substring(0, lastIndex); // 去掉扩展名
            }
            // 添加.html后缀
            fileName += ".html";
        }
        FileUtils.createFile(RuoYiConfig.getUploadPath() + "/show/" + fileName.split("\\.", 2)[0]);
        // 将文件保存到指定目录
        File outputFile = new File(RuoYiConfig.getUploadPath() + "/show/" + fileName.split("\\.", 2)[0] + "/" + fileName);
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"))) {
            if (StringUtils.isNotEmpty(htmlContentVO.getContent()))
                writer.write(htmlContentVO.getContent());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = null;
        String xhPath = "http://218.108.11.22:8093/profile-api";
        if (uploadSwitch == 1) {
            url = xhPath + "/upload/show/" + fileName.split("\\.", 2)[0] + "/" + fileName;
        } else {
            url = serverConfig.getUrl() + "/profile/upload/show/" + fileName.split("\\.", 2)[0] + "/" + fileName;
        }
        return AjaxResult.success(url);
    }
 
 
    public static void convertDocToHtml(String docFilePath, String outputHtmlFilePath) throws TransformerException, IOException, ParserConfigurationException {
 
        InputStream inputStream = new FileInputStream(docFilePath);
        HWPFDocument document = new HWPFDocument(inputStream);
        org.w3c.dom.Document htmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(htmlDoc);
 
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            @Override
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                String base64 = Base64.getEncoder().encodeToString(content);
                String src = "data:" + pictureType.getMime() + ";base64," + base64;
                return src;
            }
        });
        try {
            wordToHtmlConverter.processDocument(document);
        } catch (Exception e) {
            e.getMessage();
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "html");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
 
        DOMSource domSource = new DOMSource(wordToHtmlConverter.getDocument());
        StreamResult streamResult = new StreamResult(new File(outputHtmlFilePath));
        transformer.transform(domSource, streamResult);
 
        System.out.println("word转html成功");
 
    }
 
 
}