文件下载

写道
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.paradise.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
* MyEclipse Struts Creation date: 06-06-2010
*
* XDoclet definition:
*
* @struts.action validate="true"
*/
public class GetAction extends Action {
/*
* Generated Methods
*/

/**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws UnsupportedEncodingException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws UnsupportedEncodingException {

{
String aFilePath = null; // 要下载的文件路径
String aFileName = null; // 要下载的文件名
FileInputStream in = null; // 输入流
ServletOutputStream out = null; // 输出流

try {

aFilePath = request.getSession().getServletContext()
.getRealPath("/")
+ File.separator + "file" + File.separator;
aFileName = request.getParameter("f");

if (aFileName.endsWith("html")){
response.setContentType("text/html;charset=utf-8");

}else if (aFileName.endsWith("pdf")){
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "filename="+aFileName);

} else if (aFileName.endsWith("doc")){
response.setContentType( "application/msword");
response.setHeader( "Content-disposition ", "inline;filename="+aFileName);

}else if (aFileName.endsWith("bmp") || aFileName.endsWith("gif") || aFileName.endsWith("jpeg") || aFileName.endsWith("jpg") || aFileName.endsWith("png")){
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);

response.setContentType("image/jpeg");


}else{
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition",
"attachment;filename=" + aFileName);
}




in = new FileInputStream(aFilePath + aFileName); // 读入文件
out = response.getOutputStream();
out.flush();
int aRead = 0;
while ((aRead = in.read()) != -1 & in != null) {
out.write(aRead);
}
out.flush();
} catch (Throwable e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;
}
}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值