原生态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 "下载文件成功";
}
}
效果:
![](https://img.haomeiwen.com/i5460809/e1e2655cb92c19b7.png)
![](https://img.haomeiwen.com/i5460809/91b4c0575d387223.png)
HTTP角度看文件下载
![](https://img.haomeiwen.com/i5460809/caafcf1eefb1529c.png)
通过Content-Type指定响应返回的类型为文件类型(application/octet-stream)。然后保存时显示的文件名,使用Content-Disposition响应头指定显示文件名为640.png。
网友评论