文件下载 简单案例
| package com.example.demo.controller; |
| |
| import java.io.*; |
| import javax.servlet.http.HttpServletResponse; |
| import org.springframework.stereotype.Controller; |
| import org.springframework.web.bind.annotation.GetMapping; |
| import org.springframework.web.bind.annotation.PathVariable; |
| |
| @Controller |
| public class FileDownloadController { |
| private static final int BUFFER_SIZE = 4096; |
| @GetMapping("/download/{fileName:.+}") |
| public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException { |
| |
| String filePath = "D:\\" + fileName; |
| File file = new File(filePath); |
| InputStream inputStream = new FileInputStream(file); |
| |
| response.setContentType("application/octet-stream"); |
| response.setContentLength((int) file.length()); |
| response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); |
| |
| OutputStream outputStream = response.getOutputStream(); |
| byte[] buffer = new byte[BUFFER_SIZE]; |
| int bytesRead = -1; |
| while ((bytesRead = inputStream.read(buffer)) != -1) { |
| outputStream.write(buffer, 0, bytesRead); |
| } |
| inputStream.close(); |
| outputStream.close(); |
| } |
| } |
http的get请求方式,下载文件
| |
| import java.net.*; |
| import java.io.*; |
| |
| public class Http { |
| public static void main(String[] args) throws Exception { |
| URL url = new URL("http://127.0.0.1:9200/download/a.txt"); |
| HttpURLConnection con = (HttpURLConnection) url.openConnection(); |
| con.setRequestMethod("GET"); |
| |
| BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); |
| String inputLine; |
| StringBuffer response = new StringBuffer(); |
| |
| while ((inputLine = in.readLine()) != null) { |
| response.append(inputLine); |
| System.out.println(inputLine); |
| } |
| in.close(); |
| |
| |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?