struts2下载word,excel等文件后缀名成了xml

在下载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;
	}
 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值