k94314517
2025-04-21 16332a341801f80d27830d2ea4e683b4ab21167c
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
package com.doumee.api.common;
 
import com.doumee.api.BaseController;
import com.doumee.core.annotation.trace.Trace;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
 
@Api(tags = "本地文件接口")
@Trace(exclude = true)
@RestController
@RequestMapping("/resource/local")
public class LocalFileAccessController extends BaseController {
 
    @Value("${resources.import-template:~/files}")
    private String resourcesPath;
 
    /**
     * 下载本地文件
     */
    @GetMapping("/download")
    public void download (@RequestParam String path, @RequestParam(required = false) String name, HttpServletResponse response) throws IOException {
        File file = new File(resourcesPath.replace("~", new File("").getCanonicalPath()) + path);
        if (!file.exists() || !file.isFile()) {
            throw new BusinessException(ResponseStatus.LOCAL_FILE_NOT_EXISTS);
        }
        ByteArrayOutputStream os = this.getOutputStream(new FileInputStream(file));
        String encodeFileName = URLEncoder.encode(StringUtils.isBlank(name) ? file.getName() : name, StandardCharsets.UTF_8.toString());
        response.setHeader("Content-Disposition","attachment;filename=" + encodeFileName);
        response.setContentType("application/octet-stream");
        response.setHeader("doumee-opera-type", "download");
        response.setHeader("doumee-download-filename", encodeFileName);
        response.getOutputStream().write(os.toByteArray());
    }
}