com.gitee.apanlh.web.util.FileWebUtils Maven / Gradle / Ivy
package com.gitee.apanlh.web.util;
import com.gitee.apanlh.util.encode.CharsetCode;
import com.gitee.apanlh.util.io.IOUtils;
import com.gitee.apanlh.util.log.Log;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
/**
* 整合返回文件或者图片资源等
* #mark 需要重构
*
* @author Pan
*/
public class FileWebUtils {
public static final String OCTET_STREAM = "application/octet-stream";
public static final String VND_MS_EXCEL = "application/vnd.ms-excel";
/**
* 构造函数
*
* @author Pan
*/
private FileWebUtils() {
// 不允许外部实例
super();
}
/**
* 添加默认下载头
*
* @author Pan
* @param response HttpServletResponse对象
* @param fileName 文件名称
*/
private static void setDownloadHeader(HttpServletResponse response, String fileName) {
// 普通文件下载类型
response.setContentType("application/x-download");
try {
response.setHeader("Content-Disposition","attachment;filename=".concat(new String(fileName.getBytes(CharsetCode.UTF_8), CharsetCode.ISO_8859_1)));
} catch (Exception e) {
Log.get().error("encoding exception cause:{}", e.getMessage(), e);
return ;
}
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
}
/**
* 下载方法(普通文件下载)返回到HttpServletResponse
*
* @author Pan
* @param response HttpServletResponse
* @param outDownloadName 输出文件名
* @param bytes 字节流
*/
public static void downloadFile(HttpServletResponse response, String outDownloadName, byte[] bytes) {
setDownloadHeader(response, outDownloadName);
IOUtils.write(bytes, ServletUtils.getOutputStream(response), false);
}
/**
* 下载方法(普通文件下载)返回到HttpServletResponse
*
默认关闭输入流
*
* @author Pan
* @param response HttpServletResponse
* @param is 输入流
* @param outDownloadName 输出文件名
*/
public static void downloadFile(HttpServletResponse response, InputStream is, String outDownloadName) {
setDownloadHeader(response, outDownloadName);
IOUtils.copy(is, ServletUtils.getOutputStream(response), true, false);
}
/**
* 输出
*
* @author Pan
* @param response 输出流
* @param bytes 字节数组
*/
public static void out(HttpServletResponse response, byte[] bytes) {
response.setContentLength(bytes.length);
IOUtils.write(bytes, ServletUtils.getOutputStream(response), false);
}
/**
* 输出图片到HttpServletResponse
*
* @author Pan
* @param response HttpServletResponse
* @param bytes 字节
*/
public static void outImage(HttpServletResponse response, byte[] bytes) {
response.setContentType("application/x-png");
response.setContentLength(bytes.length);
IOUtils.write(bytes, ServletUtils.getOutputStream(response), false);
}
}