struts上传下载实现

在god老大的激励之下,我开始着手做这个上传下载了,由于它只是个作业,所以我能做的就是完成它,完美和时间的权衡下,时间最重要,我花了一个星期使用不熟练的struts来写程序,对于struts的精神理解已经很透彻了,只是struts标签库里的东西,各种form还没有完全熟悉,呵呵,反正god老大的东西不要struts开发,这也为程序留下缺陷埋下伏笔。下面列出我的代码:

上传:

selfile.jsp

<%@ page language="java"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>





------------------------------------------------------------------------------------

UploadForm.java

package com.vv.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.*;

/**
*

Title:UpLoadForm


*

Description: QRRSMMS


*

Copyright: Copyright (c) 2004 jiahansoft


*

Company: jiahansoft


* @author wanghw
* @version 1.0
*/

public class UploadForm extends ActionForm {

 public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";

 protected FormFile theFile;
 public FormFile getTheFile() {
  return theFile;
 }
 public void setTheFile(FormFile theFile) {
  this.theFile = theFile;
 }
 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
 {
  ActionErrors errors = null;
  //has the maximum length been exceeded?
  Boolean maxLengthExceeded = (Boolean)
  request.getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
  if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue()))
  {
   errors = new ActionErrors();
   errors.add(ERROR_PROPERTY_MAX_LENGTH_EXCEEDED, new ActionError("maxLengthExceeded"));
  }
  return errors;

 }
}

-------------------------------------------------------------------------------------

UploadAction.java

package com.vv.struts.action;

import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import com.vv.struts.form.UploadForm;

/**
*

Title:UpLoadAction


*

Description: QRRSMMS


*

Copyright: Copyright (c) 2004 jiahansoft


*

Company: jiahansoft


* @author wanghw
* @version 1.0
*/

public class UploadAction extends Action {
 
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
 if(form==null) System.out.println("null");
 if (form instanceof UploadForm) {//如果form是uploadsForm
  String encoding = request.getCharacterEncoding();
  if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
  {
   response.setContentType("text/html; charset=gb2312");//如果没有指定编码,编码格式为gb2312
  }
  UploadForm theForm = (UploadForm ) form;
  FormFile file = theForm.getTheFile();//取得上传的文件
  try {
   InputStream stream = file.getInputStream();//把文件读入
   String filePath = request.getRealPath("/");//取当前系统路径
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   OutputStream bos = new FileOutputStream(filePath + "/file/" +
     file.getFileName());//建立一个上传文件的输出流
   //System.out.println(filePath+"/"+file.getFileName());
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
    bos.write(buffer, 0, bytesRead);//将文件写入服务器
   }
   bos.close();
   stream.close();
  }catch(Exception e){
   System.err.print(e);
  }
  //request.setAttribute("dat",file.getFileName());
  return mapping.findForward("success");
 }
 return null;
}
}
其它的都是几个次要的页面,老实这部分基本上就是我抄的,虽然我也能写,但是他确实比我写的好,特别是对struts的字段的使用,这些都是我不知道的,我做的只是修改成我要的程序,唯一不好的就是它使用request.getRealPath("/"),这个方法很危险,可是一时间我没有找到更好的方法代替它,这些是可以避免的,为什么使用它和后面的下载有关系,呵呵。

下载:

test.jsp


<%@ page language="java"%>

here

---------------------------------------------------------------------------

download.jsp


<%@ page language="java" contentType="text/html;charset=UTF-8"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-template" prefix="template" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested" %>

xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">




 
 
 
  


  
  

  


 
 

对于struts的标签一直不是很理解,在做这个的时候受了不少的苦呀,原来iterate里的row可以作为html:link的属性值,我一直都不知道怎么来动态生成需要的链接,看了好多的例子,甚至在action里要输出到jsp的字符串上再加入字符串“”,然后用来输出,可惜struts似乎使用了回压字符流的,这个方案失败了,看了动态生成复选框的例子后明白了,修改了后就能用了,中间有个小插曲,我把paramName改为list,然后把,结果把list里的所有值作为一个单独的链接重复list.size()次输出,而不是把list的每个值重复输出list.size()次,原理其实很简单,只是感叹struts的作者写这个好像废了不少的心呀。

DownloadAction.java

package com.vv.struts.action;

import org.apache.struts.action.*;
import javax.servlet.http.*;

import java.io.File;
import java.util.*;
/**
 *

Title:DownloadWordAction


 *

Description: QRRSMMS


 *

Copyright: Copyright (c) 2004 jiahansoft


 *

Company: jiahansoft


 * @author wanghw
 * @version 1.0
 */

public class DownloadAction extends Action {
 
 File myDir;
 File[] contents;

  public ActionForward execute(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
      throws Exception {
    DynaActionForm testForm = (DynaActionForm)form;
    testForm.set("name","a test word");
   
    ArrayList list = new ArrayList();
    String path=request.getRealPath("/")+"file";
    String FullPath;
   System.out.println(path);
 myDir=new File(path);
 list.clear();
 contents=myDir.listFiles();
 //HashMap row = new HashMap();
 //System.out.println(contents.length);
 for(int i=0;i  FullPath=contents[i].getName();
  //row.put("1",FullPath);
  list.add(FullPath);
  System.out.println(FullPath);
 }
    request.setAttribute("list",list);
   
    return mapping.findForward("display");
}
}

又用了限制级的方法,我也不想的我已用相对路径它就报错,我必须承认,这个写的不够标准,应该用资源文件存储文件路径,而不是反复列举,为什么我不用呢?我当时忘了可以用资源文件了。。。。。。。

LoadedForm.java

package com.vv.struts.form;

import org.apache.struts.action.ActionForm;

/**
 * MyEclipse Struts
 * Creation date: 05-18-2006
 *
 * XDoclet definition:
 * @struts:form name="loadedForm"
 */
public class LoadedForm extends ActionForm {

 // --------------------------------------------------------- Instance Variables

 /** name property */
 private String name;

 /**
  * Returns the name.
  * @return String
  */
 public String getName() {
  return name;
 }

 /**
  * Set the name.
  * @param name The name to set
  */
 public void setName(String name) {
  this.name = name;
 }

}

---------------------------------------------------------------------------------

LoadedAction.java

package com.vv.struts.action;

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;

import java.io.*;
import com.vv.struts.form.LoadedForm;
/**
 * MyEclipse Struts
 * Creation date: 05-17-2006
 *
 * XDoclet definition:
 * @struts:action validate="true"
 */
public class LoadedAction extends Action {

 // --------------------------------------------------------- Instance Variables

 // --------------------------------------------------------- Methods

 /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) throws Exception{
 
  LoadedForm doc=(LoadedForm)form;
  //if(form==null) System.out.println("null");
  String docName = doc.getName();
  File f;
  if(docName!=""){
  String docFullPath=request.getRealPath("/");
  //System.out.println(docFullPath);
 
  String Name = docName.substring(0,docName.lastIndexOf("."));
        String prefix = docName.substring(docName.lastIndexOf("."));
        //byte[] dn=Name.getBytes("UTF-8");
        //Name =new String(dn,"ISO-8859-1");
      //Name=java.net.URLEncoder.encode(Name,"GBK");
        docName = Name +prefix;
     
      System.out.println();
      System.out.println(docName);
    
      f = new File(docFullPath+"file//"+docName);
     if (!f.exists())
     {
            return (mapping.findForward("nofile"));
     }
    
     BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
     byte[] buf = new byte[1024];
     int len = 0;
     response.reset();       
    
    
     response.setContentType("application/x-msdownload;charset=UTF-8");
     response.setHeader("Content-Disposition", "attachment; filename=" +docName);


      OutputStream out = response.getOutputStream();
      while((len = br.read(buf)) >0)
      out.write(buf,0,len);
      br.close();
      out.close();
      return mapping.findForward("download");
 }
  return mapping.findForward("nofile");
 }
 }

我还是不幸运的遇见中文乱码问题,如果下载的是中文文件的话,那么name的值就是乱码,虽然我用了转换字符的代码,可惜事实上它没有用,在:http://www.mx68.com/WebDeveloper/Print.asp?ArticleID=41762&Page=1中的三个方法我都使用了,可是都没什么太大的变化,只是显示不同的乱码而已,郁闷。实在不行了,只能把这篇不怎么样的作业上交god了。作为个程序员来说,它应该是追求完美的,但是我认为效率和时间是个凸函数,并不是但方面的极致就是最好,两者的最佳切合点才是最好。

你可能感兴趣的:(j2se)