文件下载 简单案例
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());
}
}