matrix.boot.common.utils.http.DownloadUtil Maven / Gradle / Ivy
package matrix.boot.common.utils.http;
import matrix.boot.common.exception.ServiceException;
import matrix.boot.common.utils.AssertUtil;
import matrix.boot.common.utils.BIOStreamUtil;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
/**
* 下载工具
* @author wangcheng
*/
public class DownloadUtil {
/**
* 文件路径
*/
private String filePath;
private DownloadUtil() {}
private DownloadUtil(String filePath) {
this.filePath = filePath;
}
/**
* 获取实例
* @param filePath 文件路径
* @return 下载实体
*/
public static DownloadUtil getInstance(String filePath) {
AssertUtil.notNullTip(filePath, "filePath");
return new DownloadUtil(filePath);
}
/**
* 下载
* @param response 响应
* @param sysFileName 系统文件名
* @param fileName 下载展示文件名
*/
public void download(HttpServletResponse response, String sysFileName, String fileName) {
OutputStream outputStream = null;
try {
try {
outputStream = response.getOutputStream();
} catch (IOException e) {
throw new ServiceException(e);
}
File file = new File(filePath, sysFileName);
try {
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), StandardCharsets.ISO_8859_1));
} catch (UnsupportedEncodingException e) {
throw new ServiceException(e);
}
response.addHeader("Content-Length", "" + file.length());
BIOStreamUtil.fileWriteStream(file, outputStream);
} finally {
BIOStreamUtil.closeStream(outputStream);
}
}
}