downloadaction.java
来自「spring+struts+hibernate做的银行系统」· Java 代码 · 共 122 行
JAVA
122 行
package cn.com.tym.admin;
import java.io.*;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
public abstract class DownloadAction extends Action
{
public static class ResourceStreamInfo
implements StreamInfo
{
private String contentType;
private ServletContext context;
private String path;
public String getContentType()
{
return contentType;
}
public InputStream getInputStream()
throws IOException
{
return context.getResourceAsStream(path);
}
public ResourceStreamInfo(String contentType, ServletContext context, String path)
{
this.contentType = contentType;
this.context = context;
this.path = path;
}
}
public static class FileStreamInfo
implements StreamInfo
{
private String contentType;
private File file;
public String getContentType()
{
return contentType;
}
public InputStream getInputStream()
throws IOException
{
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
return bis;
}
public FileStreamInfo(String contentType, File file)
{
this.contentType = contentType;
this.file = file;
}
}
public static interface StreamInfo
{
public abstract String getContentType();
public abstract InputStream getInputStream()
throws IOException;
}
protected static final int DEFAULT_BUFFER_SIZE = 4096;
public DownloadAction()
{
}
protected abstract StreamInfo getStreamInfo(ActionMapping actionmapping, ActionForm actionform, HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse)
throws Exception;
protected int getBufferSize()
{
return 4096;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
StreamInfo info = getStreamInfo(mapping, form, request, response);
String contentType = info.getContentType();
InputStream stream = info.getInputStream();
try
{
response.setContentType(contentType);
copy(stream, response.getOutputStream());
}
finally
{
if(stream != null)
stream.close();
}
return null;
}
public int copy(InputStream input, OutputStream output)
throws IOException
{
byte buffer[] = new byte[getBufferSize()];
int count = 0;
for(int n = 0; -1 != (n = input.read(buffer));)
{
output.write(buffer, 0, n);
count += n;
}
return count;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?