whywhyo
2023-09-25 9a5bfe21d247dbd45baedccc28f687a943c647ce
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
package com.ruoyi.service.impl;
 
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.service.DownLoadFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
 
/**
 * @Version 1.0
 * @Author Jin_quan Ou
 * @Date 2023-03-19 17:33
 */
@Service
@Slf4j
public class DownLoadFileServiceImpl implements DownLoadFileService {
 
    @Override
    public void downLoadFile(String path, HttpServletResponse response) {
 
        path = path.substring(8);
        try {
            if (!FileUtils.checkAllowDownload(path)) {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", path));
            }
            String realFileName = System.currentTimeMillis() + path.substring(path.indexOf("_") + 1);
            String filePath = RuoYiConfig.getProfile() + path;
 
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
 
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}