随笔 - 15  文章 - 1  评论 - 0  阅读 - 1811

文件下载案例

文件下载 简单案例

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();
// System.out.println(response.toString());
}
}
posted on   x-cuke  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示