首页 > Linux操作系统 > Linux操作系统 > Struts实现文件上传与下载
第一步:编写页面文件
<%@ page language="java" pageEncoding="UTF-8"%>
| 请选择要上传的文件 | |
我要下载 |
http://struts.apache.org/dtds/struts-config_1_2.dtd">
第三步:FileUploadForm.java
public class FileUploadForm. extends ActionForm
{
private FormFile filePath; //类型为FormFile,变量filePath与页面的file名称一致。
public FormFile getFilePath()
{
return filePath;
}
public void setFilePath(FormFile filePath)
{
this.filePath = filePath;
}
}
第四步:FileUploadAction.java
public class FileUploadAction extends DispatchAction
{
/**
* 上传文件
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward upload(ActionMapping mapping, ActionForm. form, HttpServletRequest request, HttpServletResponse response)throws Exception
{
FileUploadForm. fileForm=(FileUploadForm)form;
FormFile file=fileForm.getFilePath();
String realPath=this.getServlet().getServletContext().getRealPath("/fileload");
if(file==null)
return mapping.findForward("error");
String filename=file.getFileName();
int size=file.getFileSize();
if(size>1024*1024)
return mapping.findForward("error");
InputStream is=null;
BufferedOutputStream bs=null;
try
{
//get a inputstream object form. uploadFile
is=file.getInputStream();
bs=new BufferedOutputStream(new FileOutputStream(realPath+"/"+filename));
byte[] buffer=new byte[20480];
int count=0;
while((count=is.read())!=-1)
bs.write(buffer, 0, count);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
bs.flush();
bs.close();
is.close();
}
return mapping.findForward("success");
}
/**
* 下载文件
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward download(ActionMapping mapping, ActionForm. form, HttpServletRequest request, HttpServletResponse response)throws Exception
{
String path=request.getParameter("path");
String realPath=this.getServlet().getServletContext().getRealPath("/"+path);
File uploadFile=new File(realPath);
InputStream is=new FileInputStream(uploadFile);
OutputStream s=response.getOutputStream();
BufferedInputStream bis=new BufferedInputStream(is);
BufferedOutputStream bos=new BufferedOutputStream(os);
//弹出下载对话框的代码
response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(path,"utf-8"));
int bytesRead=0;
byte[] buffer=new byte[8192];
while((bytesRead=bis.read(buffer, 0, 8192))!=-1)
bos.write(buffer, 0, bytesRead);
bos.close();
is.close();
bis.close();
os.close();
return null;
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7464531/viewspace-621674/ ,如需转载,请注明出处,否则将追究法律责任。