您的位置:首页 > 编程语言 > Java开发

Struts实现文件上传与下载

2012-04-26 07:14 447 查看
第一步:编写页面文件

<%@ 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;

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息