cloudroam
2024-12-26 3493a1f3ee3010cdca1013dd11c97e551101df58
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
package com.mzl.flower.web.upload;
 
import com.mzl.flower.base.BaseController;
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.dto.response.upload.UploadResultDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
 
@RestController
@RequestMapping("/api/download")
@Api(value = "文件下载", tags = "文件下载")
@Slf4j
public class FileDownloadResource extends BaseController {
 
    @GetMapping("/file")
    @ResponseBody
    @ApiOperation(value = "文件下载", httpMethod = "GET", response = UploadResultDTO.class, notes = "文件下载")
    public void downloadFile(final String fileName, final String filePath, HttpServletResponse response) throws IOException {
        URL url = new URL(filePath);
        URLConnection uc = url.openConnection();
        String contentType = uc.getContentType();
        int contentLength = uc.getContentLength();
        if (contentType.startsWith("text/") || contentLength == -1) {
            throw new ValidationException("文件为空");
        }
        try (InputStream raw = uc.getInputStream()) {
            InputStream in = new BufferedInputStream(raw);
            byte[] data = new byte[contentLength];
            int offset = 0;
            while (offset < contentLength) {
                int bytesRead = in.read(data, offset, data.length - offset);
                if (bytesRead == -1) {
                    break;
                }
                offset += bytesRead;
            }
            if (offset != contentLength) {
                throw new ValidationException("文件为空");
            }
            // 清空response
            response.reset();
            // 设置response的Header
            /*String name = fileName;
            if(name != null){
                name = new String(name.getBytes("gb2312"), "ISO8859-1");
            }*/
            response.addHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
            response.addHeader("Content-Length", "" + contentLength);
            response.setContentType("application/octet-stream");
            try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
                out.write(data);
                out.flush();
            }
        }
    }
}