在用Java開發企業器系統的使用,特別是涉及到與辦公相關的軟體開發的時候,檔案的上傳是客戶經常要提到的要求.因此有 一套很好檔案上傳的解決辦法也能方便大家在這一塊的開發.
首先申明,該文章是為了自己記錄一備以後開發需要的時候,不用手忙腳亂哈哈........
現在在國內用的非常多的一般是兩種方法解決來解決檔案上傳.
cos.jar + uploadbean.jar + filemover.jar
這個是用的非常普遍的,原因是因為他操作方便,是我們不必再去關注,那些檔案的輸入和輸出資料流,使我們從底層的流中解脫出來.
UploadFile,UploadBean,MultipartFormDataRequest
<%@ page contentType="text/html;charset=gb2312" %>
<head>
<title>fbysss UploadBean 樣本</title>
<!--meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"-->
<!--meta http-equiv="Content-Type" content="text/html; charset=gb2312"-->
</head>
<FORM name="form1" METHOD="POST" ACTION="sssupload.jsp" ENCTYPE="multipart/form-data">
<input name="title" type= "text" value="中文字">
<td class="bodystyle">附件</td>
<td class="bodystyle"> <input name="attach" type="FILE" id="attach" size="50" > </td>
<input name="ok" type= "submit" value="提交">
</form>
2.讀取表單頁面sssgetdata.jsp
<!--
//==========================================================================
//檔案:UploadBean上傳執行個體
//功能:解決中文亂碼,完成檔案上傳,並提供上傳改名解決方案
//作者:fbysss
//msn:jameslastchina@hotmail.com
//==========================================================================
-->
<%@ page contentType="text/html;charset=GBK" %>
<%@ page language="java" import="com.jspsmart.upload.*"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="java.io.File"%>
<%@ page import="java.util.*"%>
<%@ page import="javazoom.upload.*"%>
<%@ page import="uploadutilities.FileMover"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<%
request.setCharacterEncoding("GBK");//設定編碼格式,就不用一個個轉碼了。
FileMover fileMover = new FileMover();//你也可以使用內建的執行個體中jsp:useBean的形式。
UploadBean upBean = new UploadBean();
MultipartFormDataRequest mrequest = null;
Hashtable files = null;
if (MultipartFormDataRequest.isMultipartFormData(request))
{
mrequest = new MultipartFormDataRequest(request,null,100*1024*1024,MultipartFormDataRequest.COSPARSER,"GBK");//注意這裡也要設定編碼參數
String sTt0 = mrequest.getParameter("title");
out.println("<br>Title0是:"+sTt0+"<br>");
String sTt1 = new String(sTt0.getBytes("ISO-8859-1"),"GBK");
out.println("<br>Title1是:"+sTt1+"<br>");
//這裡用來測試title參數是否正確。調試的時候,加一句if (true)return;即可。
files = mrequest.getFiles();
}
//擷取修改前的檔案名稱
String sOldFileName =mrequest.getParameter("oldfilename");
out.println("sOldFileName:"+sOldFileName);
String sWebRootPath = request.getRealPath("/");//得到你的web應用的根。
String sPath=sWebRootPath+"attach";
int iFileCount = 0;
String sServerFileName="";
String sLocalFileName = "";
//檔案擷取
if ( (files != null) || (!files.isEmpty()) ) {
iFileCount = files.size();
UploadFile file = (UploadFile) files.get("attach");
sLocalFileName=file.getFileName();
out.println("sLocalFileName:"+sLocalFileName);
int ii= sLocalFileName.indexOf("."); //取檔案名稱的尾碼
String sExt = sLocalFileName.substring(ii,sLocalFileName.length());
//得到不重複的檔案名稱
java.util.Date dt = new java.util.Date(System.currentTimeMillis());
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
sServerFileName= fmt.format(dt);
sServerFileName =sServerFileName + sExt;
//如果不存在該目錄,則建立一個
File dir =new File(sPath);
if (!dir.exists()){
dir.mkdirs();
}
upBean.setFolderstore(sPath);//設定要上傳的目錄
upBean.addUploadListener(fileMover);//增加filMover監聽
fileMover.setNewfilename(sServerFileName);//設定伺服器上的檔案名稱
upBean.store(mrequest, "attach");//上傳
out.println("file path is "+sPath+"/"+sServerFileName);
}
%>
Demo注意事項:cos.jar,uploadbean.jar,filemover.jar這幾個包必須有。
必備:
UploadBean1.5:http://wcarchive.cdrom.com/pub/simtelnet/winnt/java/uploadbean1_5.zip
FileMover1.3:http://www.javazoom.net/jzservlets/uploadbean/addons/filemover1.3.zip
參考:
ChinesUpload例子:http://www.javazoom.net/jzservlets/uploadbean/addons/ChineseUpload.zip
參考了fbysss的一篇文章
2. org.apache.struts.upload.FormFile
Struts1.1的org.apache.struts.upload.FormFile類。很方便,不用自己寫。也不用寫一個jsp調用jspsmartupload就可以搞定。
選擇上傳檔案頁面:selfile.jsp
--------------------------------------------------------------------------------
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html:html>
<html:form action="/uploadsAction.do" enctype="multipart/form-data">
<html:file property="theFile"/>
<html:submit/>
</html:form>
</html:html>
--------------------------------------------------------------------------------
UpLoadAction.java
--------------------------------------------------------------------------------
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
/**
* <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 instanceof uploadsForm) {//如果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.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("display");
}
return null;
}
}
--------------------------------------------------------------------------------
UpLoadForm.java
--------------------------------------------------------------------------------
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;
}
}
//這是相對應的form,還有其他屬性可以設定,具體可以參考struts的上傳例子。
--------------------------------------------------------------------------------
struts-config.xml
--------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd";>
<struts-config>
<form-beans>
<form-bean name="uploadsForm" type="UpLoadForm" />
</form-beans>
<action-mappings>
<action name="uploadsForm" type="UpLoadAction" path="/uploadsAction">
<forward name="display" path="/display.jsp" />
</action>
</action-mappings>
</struts-config>
<!--display.jsp就是隨便寫一個成功頁-->