Struts实现文件上传与下载

来源:互联网 发布:淘宝销量第一的店铺 编辑:程序博客网 时间:2024/06/05 10:19

第一步:编写页面文件

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <
%@includefile="/header.jsp"%>
    <title>struts上传文件</title>
  </head>
  <body>
   <h2>使用
Struts上传文件</h2>
     <hr/>
    <form. action="<%=basePath%>strutsfileupload.do?method=upload" method="post"
           enctype="multipart/form-data">
       <table>
         <tr>
           <td>请选择要上传的文件</td>
           <td>
              <input type="file" name="filePath" size="20"/><br/>
           </td>
         </tr>
         <tr>
            <td>
              <input type="submit" value="上传"/>
            </td>
            <td>
              <a href="<%=basePath%>strutsfileupload.do?method=download&path=fileload/xxxx.txt">我要下载</a>
            </td>
         </tr>
        </table>
    </form>
  </body>
</html>
第二步:struts-config.xml文件,包含form-bean 和action的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "
http://struts.apache.org/dtds/struts-config_1_2.dtd">
 <data-sources />
 <form-beans >
      <form-bean name="fileUploadForm"
            type="com.xinglongjian.struts.fileupload.FileUploadForm" />
 </form-beans>
 <global-exceptions />
 <global-forwards>
  <forward name="error" path="/error/sysError.jsp"></forward>
 </global-forwards>
 <action-mappings>
  <action path="/strutsfileupload" parameter="method" name="fileUploadForm"
            type="com.xinglongjian.struts.fileupload.FileUploadAction" >
              <forward name="success" path="/struts/success.jsp"></forward>
        </action>
 </action-mappings>
</struts-config>

第三步: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;
 }
}

原创粉丝点击