美文网首页
分析文件下载

分析文件下载

作者: sunpy | 来源:发表于2024-06-15 20:35 被阅读0次

原生态js实现文件下载

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="sunpeiyu文件下载">
    <meta name="author" content="sunpeiyu">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <title>Document</title>
    <style type="text/css">
        body {
            background-color: white;
        }
    </style>

    <script type="text/javascript">
        function downloadFile() {
            const link = document.createElement('a');
            link.style.display = 'none';
            link.download = '640.png';
            link.href = 'http://localhost:8091/diverter/file/download/640.png';
            link.click();
        }
    </script>
</head>

<body>
    <div>
        <a href="#" onclick="downloadFile()">文件下载</a>
    </div>
</body>
</html>

springboot实现文件下载

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@RequestMapping("/file")
@RestController
public class FileController {

    @GetMapping("/download/{fileName}")
    public String handleFileDownload(@PathVariable String fileName,
                                     HttpServletResponse response,
                                     HttpServletRequest request) throws IOException {
        String downloadFilePath = "F:\\temp" + File.separator + fileName;

        if (!FileUtil.exist(downloadFilePath)) {
            return "下载文件不存在";
        }

        byte[] fileByteArr = FileUtil.readBytes(downloadFilePath);

        /**
         * 解决跨域请求问题
         */
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE,PATCH");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        response.setHeader("Content-Type", "application/octet-stream");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(fileByteArr);
        outputStream.flush();
        outputStream.close();
        return "下载文件成功";
    }
}

效果:



HTTP角度看文件下载


通过Content-Type指定响应返回的类型为文件类型(application/octet-stream)。然后保存时显示的文件名,使用Content-Disposition响应头指定显示文件名为640.png。

相关文章

网友评论

      本文标题:分析文件下载

      本文链接:https://www.haomeiwen.com/subject/apezqjtx.html