DIV CSS 佈局教程網

用 JSP 實作檔案上傳的兩種常見方案
編輯:JavaScript綜合知識     

過去我們常用 cos 這套元件來處理檔案上傳,但上傳完成後若想替檔案改名,往往還得再借助其他工具,流程顯得繁瑣。

在企業級 Java 開發中,尤其是與辦公自動化相關的系統裡,「檔案上傳」幾乎是客戶必提的需求。因此擁有一套完善的上傳解決方案,能大幅降低這部分的開發成本。以下整理兩種在業界相當普遍的實作方式,供日後開發時參考取用。

方案一:cos.jar + uploadbean.jar + filemover.jar

這是使用率極高的一組組合,原因在於操作直覺——我們不必再親自處理檔案的輸入與輸出串流,等於把底層的串流細節都封裝掉了。核心類別包括 UploadFile、UploadBean 與 MultipartFormDataRequest。

表單頁面(例如 sssupload.jsp)的撰寫方式如下:

<%@ page contentType="text/html;charset=gb2312" %>
<head>
<title>fbysss UploadBean 示例</title>
</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>

讀取表單並完成上傳(sssgetdata.jsp)

<!--
//==========================================================================
//檔案:UploadBean 上傳實例
//功能:解決中文亂碼、完成檔案上傳,並提供上傳改名方案

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);//加入 fileMover 監聽
fileMover.setNewfilename(sServerFileName);//設定伺服器上的檔名
upBean.store(mrequest, "attach");//上傳
out.println("file path is " + sPath + "/" + sServerFileName);
}

%>

使用此範例時務必準備好 cos.jar、uploadbean.jar、filemover.jar 這三個套件,缺一式便無法運作。

方案二:org.apache.struts.upload.FormFile

Struts 1.1 提供的 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;

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");
}
UpLoadForm theForm = (UpLoadForm) form;
FormFile file = theForm.getTheFile();//取得上傳檔案
try {
InputStream stream = file.getInputStream();//將檔案讀入
String filePath = request.getRealPath("/");//取得目前系統路徑
OutputStream bos = new FileOutputStream(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);
}
return mapping.findForward("display");
}
return null;
}
}

UpLoadForm.java:

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

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;
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" "https://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 只是一個成功後顯示的頁面-->

資料來源:CSDN

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved