能不能给出比较全面的方法,包含通过response返回给前端,包含各种异常处理
时间: 2024-09-18 16:07:13 浏览: 40
当然可以,下面是一个更为全面的方法,包含了通过Response返回文件给前端,同时也处理了常见的异常情况:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
public class FileDownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("filename"); // 假设前端传入文件名
String filePath = "/path/to/files/" + fileName; // 文件的实际路径
try {
// 创建URL对象
URL url = new URL(filePath);
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 请求文件
conn.setDoOutput(true); // 设置允许输出
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 开始接收输出流
OutputStream outputStream = response.getOutputStream();
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024]; // 块大小
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
// 关闭流并断开连接
outputStream.flush();
outputStream.close();
inputStream.close();
conn.disconnect();
} catch (MalformedURLException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid file path or URL.");
e.printStackTrace();
} catch (IOException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred during the file download.");
e.printStackTrace();
}
}
}
// 当前端访问/download?filename=your_file.txt时,就会触发这个下载请求
```
这个Servlet会在接收到GET请求后尝试从指定的URL下载文件,并将结果返回给前端。如果发生URL无效、IO错误或其他异常,它会返回适当的HTTP状态码和错误信息。
阅读全文