在下载2007版的word,excel等文件时,下载下来的时候总是xml,如果用word或者excel打开的时候确实还是原来的内容,但这让用户体验完全不行。
经过我的测试,确认是我们在生成流时指定的返回类型标签不对造成的,只要指定了正确的返回类型就没问题了
代码如下:
根据扩展名指定返回的类型
/**
* 根据拓展名取的类型
* @param extension
* @return String
*/
public static String getContentValue(String extension ){
if(extension.equalsIgnoreCase("dotx")){
return dotx ;
}else if(extension.equalsIgnoreCase("docx")){
return docx ;
}else if(extension.equalsIgnoreCase("xlsx")){
return xlsx ;
}else if(extension.equalsIgnoreCase("pptx")){
return pptx ;
}else{
return "application/octet-stream;charset=ISO8859-1";
}
}
返回struts2的标签
@Results( { @Result(name = "success", location = "attachment-file.jsp"),
@Result(name = "download", type = "stream", params = { "contentType","${contentType}",
"inputName", "inputStream",
"contentDisposition","filename=${downAttachmentName}",
"bufferSize","4096" ,
"inputPath", "${downAttachmentUrl}"
})
})
下载的代码
/**
* 附件下载
* @return String
*/
public String downloadAttachment() throws Exception {
try {
String id = Struts2Utils.getRequest().getParameter("sid");
if(StrUtil.isEmptyWithTrim(id)){
return showError("参数传递错误!");
}
AttachmentStore ps;
try {
ps = attachmentStoreManager.getAttachment(id);
downAttachmentName = ps.getAttachmentName()+"."+ps.getAttachmentType();
logger.info("下载extension-------"+ps.getAttachmentType());
String contentType = Constant.getContentValue(ps.getAttachmentType());
logger.info("下载contentType-------"+contentType);
setContentType(contentType);
//downAttachmentName = new String(downAttachmentName.getBytes(), "iso8859-1");
//downAttachmentName = new String(downAttachmentName.getBytes(), "ISO8859-1");
downAttachmentName = java.net.URLEncoder.encode(downAttachmentName, "UTF-8"); //linux下解决乱码
downAttachmentUrl = ps.getAbsolutePath()+ps.getSid()+"."+ps.getAttachmentType();
} catch (AttachmentStoreException e) {
logger.error("附件查询失败,附件已经不存在或被删除"+e);
ps = null;
}
if(ps == null){
return showError("附件已经不存在或被删除!");
}
} catch (Exception e) {
throw new Exception("");
}
return "download";
}
/**
* 打开附件下载流
* @return InputStream
*/
public InputStream getInputStream() throws Exception {
InputStream input1 = null;
try {
logger.info("getInputStream--");
input1 = new FileInputStream(downAttachmentUrl);
} catch (Exception e) {
throw new Exception("");
}
return input1;
}