在god老大的激勵(lì)之下,我開始著手做這個(gè)上傳下載了,由于它只是個(gè)作業(yè),所以我能做的就是完成它,完美和時(shí)間的權(quán)衡下,時(shí)間最重要,我花了一個(gè)星期使用不熟練的struts來寫程序,對于struts的精神理解已經(jīng)很透徹了,只是struts標(biāo)簽庫里的東西,各種form還沒有完全熟悉,呵呵,反正god老大的東西不要struts開發(fā),這也為程序留下缺陷埋下伏筆。下面列出我的代碼:
上傳:
selfile.jsp
<%@ page language="java"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<html:html>
<html:form action="/upload.do" enctype="multipart/form-data">
<html:file property="theFile"/>
<html:submit/>
</html:form>
</html:html>
------------------------------------------------------------------------------------
UploadForm.java
package com.vv.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.*;
/**
* <p>Title:UpLoadForm</p>
* <p>Description: QRRSMMS </p>
* <p>Copyright: Copyright (c) 2004 jiahansoft</p>
* <p>Company: jiahansoft</p>
* @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;
/**
* <p>Title:UpLoadAction</p>
* <p>Description: QRRSMMS </p>
* <p>Copyright: Copyright (c) 2004 jiahansoft</p>
* <p>Company: jiahansoft</p>
* @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("/");//取當(dāng)前系統(tǒng)路徑
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + "/file/" +
file.getFileName());//建立一個(gè)上傳文件的輸出流
//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);//將文件寫入服務(wù)器
}
bos.close();
stream.close();
}catch(Exception e){
System.err.print(e);
}
//request.setAttribute("dat",file.getFileName());
return mapping.findForward("success");
}
return null;
}
}
其它的都是幾個(gè)次要的頁面,老實(shí)這部分基本上就是我抄的,雖然我也能寫,但是他確實(shí)比我寫的好,特別是對struts的字段的使用,這些都是我不知道的,我做的只是修改成我要的程序,唯一不好的就是它使用request.getRealPath("/"),這個(gè)方法很危險(xiǎn),可是一時(shí)間我沒有找到更好的方法代替它,這些是可以避免的,為什么使用它和后面的下載有關(guān)系,呵呵。
下載:
test.jsp
<%@ page language="java"%>
<a href="/other/download.do">here</a>
---------------------------------------------------------------------------
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" %>
<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<style>
</style>
</head>
<body>
<bean:write name="DownWordForm" property="name" />
<logic:notEmpty name="list" >
<logic:iterate id="row" name="list">
<p><html:link page="/loaded.do" paramId="name" paramName="row">
<bean:write name="row"/>
</html:link>
</p>
</logic:iterate>
</logic:notEmpty>
</body>
</html>
對于struts的標(biāo)簽一直不是很理解,在做這個(gè)的時(shí)候受了不少的苦呀,原來iterate里的row可以作為html:link的屬性值,我一直都不知道怎么來動(dòng)態(tài)生成需要的鏈接,看了好多的例子,甚至在action里要輸出到j(luò)sp的字符串上再加入字符串“<html:link.......>”,然后用<bean:write>來輸出,可惜struts似乎使用了回壓字符流的,這個(gè)方案失敗了,看了動(dòng)態(tài)生成復(fù)選框的例子后明白了,修改了后就能用了,中間有個(gè)小插曲,我把paramName改為list,然后把<bean:write name="list">,結(jié)果把list里的所有值作為一個(gè)單獨(dú)的鏈接重復(fù)list.size()次輸出,而不是把list的每個(gè)值重復(fù)輸出list.size()次,原理其實(shí)很簡單,只是感嘆struts的作者寫這個(gè)好像廢了不少的心呀。
DownloadAction.java
package com.vv.struts.action;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.io.File;
import java.util.*;
/**
* <p>Title:DownloadWordAction </p>
* <p>Description: QRRSMMS </p>
* <p>Copyright: Copyright (c) 2004 jiahansoft</p>
* <p>Company: jiahansoft</p>
* @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<contents.length;i++){
FullPath=contents[i].getName();
//row.put("1",FullPath);
list.add(FullPath);
System.out.println(FullPath);
}
request.setAttribute("list",list);
return mapping.findForward("display");
}
}
又用了限制級的方法,我也不想的我已用相對路徑它就報(bào)錯(cuò),我必須承認(rèn),這個(gè)寫的不夠標(biāo)準(zhǔn),應(yīng)該用資源文件存儲(chǔ)文件路徑,而不是反復(fù)列舉,為什么我不用呢?我當(dāng)時(shí)忘了可以用資源文件了。。。。。。。
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");
}
}
我還是不幸運(yùn)的遇見中文亂碼問題,如果下載的是中文文件的話,那么name的值就是亂碼,雖然我用了轉(zhuǎn)換字符的代碼,可惜事實(shí)上它沒有用,在:http://www.mx68.com/WebDeveloper/Print.asp?ArticleID=41762&Page=1中的三個(gè)方法我都使用了,可是都沒什么太大的變化,只是顯示不同的亂碼而已,郁悶。實(shí)在不行了,只能把這篇不怎么樣的作業(yè)上交god了。作為個(gè)程序員來說,它應(yīng)該是追求完美的,但是我認(rèn)為效率和時(shí)間是個(gè)凸函數(shù),并不是但方面的極致就是最好,兩者的最佳切合點(diǎn)才是最好。