# Struts2 附件檔案下載功能
[前情提要](https://hackmd.io/1XW2--RGSgmDxelLUtXUBQ)
```htmlmixed=\
<s:hidden id="fileName" name="fileName" />
<s:hidden id="mailAttSeq" name="mailAttSeq" />
<tr>
<th>附件</th>
<td>
<s:iterator value="%{mailMaintainDetailVo.mailAttachmentList}">
<s:property value="fileName"/>
<input name="btnEnter" type="button" class="btnHL" value="下載" onclick="mailAttachmentDownload('<s:property value="fileName"/>','<s:property value="mailAttSeq"/>')" />
<br>
</s:iterator>
</td>
</tr>
```
```javascript=\
function mailAttachmentDownload(fileName,mailAttSeq) {
jQuery("#fileName").val(fileName);
jQuery("#mailAttSeq").val(mailAttSeq);
jQuery("#mailMaintainDetailform").attr('action', 'mailAttachmentDownload').submit();
}
```
```java=\
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
private InputStream stream;
private String fileName;
private String mailAttSeq;
...getter setter
@Action(value = "mailAttachmentDownload", results = {@Result(name ="success", type = "stream", params = {"contentType",
"application/octet-stream","inputName", "stream", "contentDisposition",
"attachment;filename=\"${fileName}\"", "bufferSize", "1024"}),
@Result(name = DETAIL, location = "sysMaintain.mailMaintainDetail.tiles", type = "tiles")})
@SkipValidation
public String mailAttachmentDownload() {
logger.info("mailAttachmentDownload");
logger.info("fileName:"+fileName);
logger.info("mailAttSeq:"+mailAttSeq);
try {
HttpServletRequest request = getHttpServletRequest();
String userAgent = request.getHeader("User-Agent");
BASE64Decoder de = new BASE64Decoder();
byte[] resultByte = null;
if (StringUtils.isNotBlank(mailAttSeq)) {
MailAttachment mailAttachment = mailDao.getMailAttachment(mailAttSeq);
logger.info("mailAttachment: "+mailAttachment);
if(mailAttachment != null) {
resultByte = de.decodeBuffer(mailAttachment.getFileBase64());
stream = new ByteArrayInputStream(resultByte);
}
}
if(userAgent.contains("IE")){ //中文檔名給予
fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
}else{
fileName= new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
}
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
//response.setHeader("Set-Cookie", "fileDownload=true; path=/");
logger.error("下載失敗 ERROR IS " + e);
message = " 下載失敗 , 發生錯誤 !" ;
return DETAIL;
}
}
```
###### tags: `javascript` `Java`