如何直接获取到HttpServletResponse中的文件,给出可以直接使用的工具类
时间: 2023-07-16 09:15:00 浏览: 86
Java service层获取HttpServletRequest工具类的方法
5星 · 资源好评率100%
可以使用以下工具类来获取HttpServletResponse中的文件:
```java
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class HttpResponseUtils {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static void write(HttpServletResponse response, byte[] data, String fileName, String contentType) throws IOException {
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType(contentType);
response.setContentLength(data.length);
response.getOutputStream().write(data);
response.getOutputStream().flush();
}
public static void write(HttpServletResponse response, byte[] data, String fileName) throws IOException {
write(response, data, fileName, "application/octet-stream");
}
public static void write(HttpServletResponse response, String text, String contentType) throws IOException {
response.reset();
response.setContentType(contentType);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
response.getWriter().flush();
}
public static void write(HttpServletResponse response, String text) throws IOException {
write(response, text, "text/plain;charset=UTF-8");
}
}
```
使用方法如下:
```java
byte[] fileBytes = getFileBytes(); // 获取文件字节数组
String fileName = "example.txt";
HttpServletResponse response = getHttpServletResponse(); // 获取HttpServletResponse对象
HttpResponseUtils.write(response, fileBytes, fileName); // 写入响应
```
其中,`getFileBytes()`方法是获取文件字节数组的方法,`getHttpServletResponse()`方法是获取HttpServletResponse对象的方法。你需要根据具体情况自行实现这两个方法。
阅读全文