下面是@WebServlet的属性列表。
从上表可见,web.xml可以配置的servlet属性,在@WebServlet中都可以配置。
@WebServlet(description = "FileDownload", urlPatterns = { "/downloadFileServlet"},loadOnStartup=1)
public class DownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 6953326785472752032L;
static Logger log = Logger.getLogger(DownloadFileServlet.class);
public void doPost(HttpServletRequest request, HttpServletResponse response) {
InputStream ism = null;
ServletOutputStream fout = null;
// 封装的时候 request 有可能会丢失
try {
String unid = ObjectUtils.toString(request.getParameter("unid"));// UNID
String fileName = ObjectUtils.toString(request.getParameter("fileName"));// 附件名称
String fileType = ObjectUtils.toString(request.getParameter("fileType"));// 附件类型
String attachmentPath = ObjectUtils.toString(request.getParameter("attachmentPath"));// 附件路径
String fileSavePath = ObjectUtils.toString(request.getParameter("fileSavePath"));// 保存路径
// 编码转换
unid = URLDecoder.decode(unid, "UTF-8");
fileName = URLDecoder.decode(fileName, "UTF-8");
fileType = URLDecoder.decode(fileType, "UTF-8");
attachmentPath = URLDecoder.decode(attachmentPath, "UTF-8");
fileSavePath = URLDecoder.decode(fileSavePath, "UTF-8");
if(attachmentPath.indexOf("http") == 0){
try {
ism = ImageUtil.readImage(attachmentPath);
} catch (Throwable e) {
log.error("文件流转换出错---",e);
}
} else if (StringUtils.isNotBlank(attachmentPath)) {
if (fileName.indexOf(".") == -1) {
fileName = fileName + "." + fileType;
}
File attrFile = new File(attachmentPath);// D:/export/save/save2016年04月01日08时53分17秒.zip
if (!attrFile.exists() || !attrFile.isFile()) {
log.error(attrFile + "文件不存在,或者不是文件。");
return;
}
// 转化为输入流
ism = new FileInputStream(attrFile);
}
if (StringUtils.isNotBlank(fileName)) {
fileName = fileName.replaceAll("[/*/?//\\<>|:]", "");// 保存名称
fileName = new String(fileName.getBytes("GBK"), "ISO8859-1"); // 中文文件名需要进行ISO8859-1转码方可正确显示
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentType("application/octet-stream");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=0");
byte[] buffer = new byte[4096];
fout = response.getOutputStream();
int bytesRead;
while ((bytesRead = ism.read(buffer, 0, buffer.length)) != -1){
try {
fout.write(buffer, 0, bytesRead);
} catch (Exception e) {
log.error("Connect reset by peer:Socket write error!"+e.getMessage(), e);
}
}
}
} catch (Exception e) {
log.error("下载异常", e);
} finally {
if (ism != null) {
try {
ism.close();
} catch (IOException e) {
}
}
if (fout != null) {
try {
fout.flush();
fout.close();
} catch (IOException e) {
}
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) {
doPost(request, response);
}
}