import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
//方法1
public ResponseEntity<byte[]> fileDownload() throws IOException {
//读取源文件
File file = new File("e://hello.txt");
InputStream is = new FileInputStream(file);
byte[] dest = null;
int fileLength = is.available();
dest = new byte[fileLength];
is.read(dest);
//创建http头并设置指定值
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + new String(file.getName().getBytes(), "ISO8859-1"));
headers.add("application/octet-stream;","charset=utf-8");
//设置HTTP响应状态。
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(dest,headers,statusCode);
return responseEntity;
}
//方法2
public HttpServletResponse fileDownload(String path, HttpServletResponse response) {
InputStream in = null;
OutputStream toClient = null;
try {
//path是指欲下载的文件的路径。
File file = new File(path);
//取得文件名。
String filename = file.getName();
//清空response
response.reset();
//设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
//以流的形式下载文件。
in = new BufferedInputStream(new FileInputStream(path));
//文件缓冲区
int b;
byte[] by = new byte[1024];
while ((b = in.read(by)) != -1) {
toClient.write(by, 0, b);
}
toClient.flush();
} catch (IOException ex) {
ex.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(toClient!=null){
try {
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
java文件下载
最新推荐文章于 2024-10-01 09:29:45 发布