java下载文件到浏览器
时间: 2023-09-04 18:12:22 浏览: 51
你可以使用Java中的URLConnection类来下载文件并将其发送到浏览器。以下是一个简单的示例代码:
```
import java.io.*;
import java.net.*;
public class DownloadFile {
public static void main(String[] args) throws IOException {
String fileUrl = "http://example.com/file.pdf";
String fileName = "file.pdf";
URL url = new URL(fileUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(fileName);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("File download failed");
}
httpConn.disconnect();
// Send file to browser
File file = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
fileInputStream.read(data);
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
response.getOutputStream().write(data);
response.getOutputStream().flush();
FacesContext.getCurrentInstance().responseComplete();
}
}
```
该代码从指定的URL下载文件,保存到指定的文件名,然后将该文件发送到浏览器。在上面的示例中,我们假设你正在使用JSF框架,并且有一个FacesContext对象可用来获取HttpServletResponse对象。如果你在使用其他框架或原生Servlet开发,则可以使用类似的方法来获取HttpServletResponse对象并将文件发送到浏览器。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)