ファイルのダウンロードにおけるいくつかの問題点--resultType Stream
, excel 。 。
jsp , :
<%@ page contentType="text/html; charset=GB2312"%>
<%@ page import="java.io.*" %>
<html>
<head></head>
<body>
<%
OutputStream o = response.getOutputStream();
byte[] b = new byte[500];
File file = new File("c:/","cgx.jpg");
// MIME , application/octet-stream
response.setContentType("image/jpeg");
// , , ,
response.setHeader("Content-Disposition", "attachment;filename=cgx.jpg");
long fileLength = file.length();
String length = String.valueOf(fileLength);
response.setHeader("Content-Length", length);
FileInputStream in = new FileInputStream(file);
int n = 0;
while((n = in.read(b)) != -1) {
o.write(b,0,n);
}
out.clear();
out = pageContext.pushBody();
// :getOutputStream() has already been called for this response
%>
</body>
</html>
JSPページの最後の2行のコードの注釈を削除して、この2行のコードの作用は以下の通りです:out.clear():キャッシュの内容を空にします.pageContext.pushBody():APIpublic BodyContent pushBody()参照
Return a new BodyContent object, save the current "out"JspWriter, and update the value of the "out"attribute in the page scope attribute namespace of the PageContext.
新しいBodyContent(HTMLページのBODY部分を表す)・JspWriterインスタンスを保存するオブジェクトout・PageContextのout属性を更新する内容を返します.
しかしstruts 2ではactionとプロファイルはそれぞれ:
public String exportSheetPart(){
this.showByRole();
return this.exportSheet();
}
public String exportSheetTotal() {
this.execute();
return this.exportSheet();
}
public String exportSheet() {
ValueStack vs = (ValueStack)ServletActionContext.getRequest().getAttribute("struts.valueStack");
UserUtil userUtil = (UserUtil)vs.findValue("userUtil");
DeptUtil deptUtil = (DeptUtil)vs.findValue("deptUtil");
CodeUtil codeUtil = (CodeUtil)vs.findValue("codeUtil");
ByteArrayOutputStream out = new ByteArrayOutputStream();
String realpath = ServletActionContext.getServletContext().getRealPath("/jsp/common/equipTemplate.xls");
try {
docName = new String(" .xls".getBytes("GBK"),"iso-8859-1");
/* out Workbook template = null;
WorkbookSettings setting = new WorkbookSettings();
java.util.Locale locale = new java.util.Locale("zh","CN");
setting.setLocale(locale);
setting.setEncoding("GBK");
template = Workbook.getWorkbook(new File(realpath),setting);
WritableWorkbook book = Workbook.createWorkbook(out,template);
WritableSheet sheet = book.getSheet(0);
WritableCellFormat wcf = new WritableCellFormat();
wcf.setAlignment(Alignment.CENTRE);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
wcf.setFont(new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE, Colour.RED));
wcf.setBorder(Border.ALL, BorderLineStyle.THIN);
WritableCellFormat ftText = new WritableCellFormat();
ftText.setAlignment(Alignment.CENTRE);
ftText.setVerticalAlignment(VerticalAlignment.CENTRE);
ftText.setFont(new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK));
ftText.setBorder(Border.ALL, BorderLineStyle.THIN);
int row = 1;
int index = 0;
String tmptMaintainDeptId;
String tmptMaintainUserId;
String tmptFixDate;
String tmptFixMethod;
for(FaMaintain result : maintainList){
if(result.getMaintainDeptId() == null) {
tmptMaintainDeptId = "";
tmptMaintainUserId = "";
} else {
tmptMaintainDeptId = result.getMaintainDeptId().toString();
tmptMaintainUserId = result.getMaintainUserId().toString();
}
if(result.getFixDate() == null) {
tmptFixDate = "";
} else {
tmptFixDate = result.getFixDate().toString();
}
if(result.getFixMethod() == null) {
tmptFixMethod = "";
} else {
tmptFixMethod = result.getFixMethod();
}
Label indexTitle = new Label(0,row,Integer.toString(index),ftText);
Label equipNumber = new Label(1,row,result.getFaEquipment().getEquipNumber(),ftText);
Label status = new Label(2,row,codeUtil.name("FA_MAINTAIN_STATUS", result.getStatus()),ftText);
Label healthStatus = new Label(3,row,codeUtil.name("FA_EQUIPMENT_HEALTH_STATUS", result.getFaEquipment().getHealthStatus()),ftText);
Label replace = new Label(4,row,codeUtil.name("FND_YESNO", result.getReplace()),ftText);
Label createUserId = new Label(5,row,userUtil.name(result.getCreateUserId().toString()),ftText);
Label createDeptId = new Label(6,row,deptUtil.name(result.getCreateDeptId().toString()),ftText);
Label createDate = new Label(7,row,result.getCreateDate().toString(),ftText);
Label priority = new Label(8,row,codeUtil.name("FA_MAINTAIN_PRIORITY", result.getPriority()),ftText);
Label maintainUserId = new Label(9,row,userUtil.name(tmptMaintainUserId),ftText);
Label maintainDeptId = new Label(10,row,deptUtil.name(tmptMaintainDeptId),ftText);
Label fixDate = new Label(11,row,tmptFixDate,ftText);
Label fixMethod = new Label(12,row,codeUtil.name("FA_MAINTAIN_METHOD", tmptFixMethod),ftText);
Label memo = new Label(13,row,result.getMemo(),ftText);
sheet.addCell(indexTitle);
sheet.addCell(equipNumber);
sheet.addCell(status);
sheet.addCell(healthStatus);
sheet.addCell(replace);
sheet.addCell(createUserId);
sheet.addCell(createDeptId);
sheet.addCell(createDate);
sheet.addCell(priority);
sheet.addCell(maintainUserId);
sheet.addCell(maintainDeptId);
sheet.addCell(fixDate);
sheet.addCell(fixMethod);
sheet.addCell(memo);
row++;
index++;
}
book.write();
book.close();*/
exportStream = new ByteArrayInputStream(out.toByteArray());// out in
}catch (Exception e) {
addActionError(" ");
e.printStackTrace();
return ERROR;
} finally {// .
try {
if (out != null) {
out.flush();
out.close();
out = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return SUCCESS;
}
<action name="equip_export" method="exportSheetPart" class="MaintainListAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
<param name="contentDisposition">attachment;fileName="${docName}"</param>
<param name="inputName">exportStream</param>
<param name="bufferSize">4096</param>
</result>
</action>
<action name="equip_export2" method="exportSheetTotal" class="MaintainListAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
<param name="contentDisposition">attachment;fileName="${docName}"</param>
<param name="inputName">exportStream</param>
<param name="bufferSize">4096</param>
</result>
</action>
jspページには、このようなjsがあります.
function exp(){
var tgt = document.queryForm.target;
var act = document.queryForm.action;
document.queryForm.target = 'sframe';
document.queryForm.action = 'equip_export.do';
document.queryForm.submit();
document.queryForm.action = act;
document.queryForm.target = tgt;
}
こんなhtmlと
<td width="40">
<table border="0" cellpadding="0" cellspacing="0" class="ButCmd-border" onMouseOver="this.className='ButCmd2-border'" onMouseOut="this.className='ButCmd-border'" >
<tr>
<td><input name="expBtn" onclick="exp();" value=" " title=" " type="button" class="btn3_mouseout" onMouseOver="this.className='btn3_mouseover'" onMouseOut="this.className='btn3_mouseout'" onMouseDown="this.className='btn3_mousedown'" onMouseUp="this.className='btn3_mouseup'" style="width:66px; height:22px;"/></td>
</tr>
</table>
</td>
<iframe src="" name="sframe" width="100%" marginwidth="0" height="0" marginheight="0" scrolling="no" frameborder="0" id="sframe"></iframe>
Return a new BodyContent object, save the current "out"JspWriter, and update the value of the "out"attribute in the page scope attribute namespace of the PageContext.
Returns:
the new BodyContent
・新しいBodyContent(HTMLページのBODY部分を表す)を返す・JspWriterインスタンスのオブジェクトoutを保存する・PageContextのout属性の内容を更新する
Returns:
the new BodyContent