熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

用JSP實現上傳文件的兩種方法

2022-06-13   來源: JSP教程 

  以前用cos作文件上傳但是對於文件上傳後的改名還需要借助其他的工具

  摘錄如下:

  
在用Java開發企業器系統的使用特別是涉及到與辦公相關的軟件開發的時候文件的上傳是客戶經常要提到的要求因此有 一套很好文件上傳的解決辦法也能方便大家在這一塊的開發

  首先申明該文章是為了自己記錄一備以後開發需要的時候不用手忙腳亂哈哈

  現在在國內用的非常多的一般是兩種方法解決來解決文件上傳

  cosjar + uploadbeanjar + filemoverjar
這個是用的非常普遍的原因是因為他操作方便是我們不必再去關注那些文件的輸入和輸出流使我們從底層的流中解脫出來
UploadFileUploadBeanMultipartFormDataRequest

  <%@ page contentType="text/html;charset=gb" %>
<head>
<title>fbysss UploadBean 示例</title>
<!meta httpequiv="ContentType" content="text/html; charset=iso">
<!meta httpequiv="ContentType" content="text/html; charset=gb">
</head>
<FORM name="form" METHOD="POST" ACTION="sssuploadjsp" ENCTYPE="multipart/formdata">
<input name="title" type= "text" value="中文字">
<td class="bodystyle">附件</td>
<td class="bodystyle"> <input name="attach" type="FILE" id="attach" size="" > </td>
<input name="ok" type= "submit" value="提交">
</form>

  讀取表單頁面sssgetdatajsp

  <!
//==========================================================================
//文件UploadBean上傳實例
//功能解決中文亂碼完成文件上傳並提供上傳改名解決方案
//作者fbysss
//msn:jameslastchina@hotmailcom
//==========================================================================
>
<%@ page contentType="text/html;charset=GBK" %>
<%@ page language="java" import="comjspsmartupload*"%>
<%@ page import="javatextSimpleDateFormat"%>
<%@ page import="javaioFile"%>
<%@ page import="javautil*"%>
<%@ page import="javazoomupload*"%>
<%@ page import="uploadutilitiesFileMover"%>
<head>
<meta httpequiv="ContentType" content="text/html; charset=gb">
</head>
<%
requestsetCharacterEncoding("GBK");//設置編碼格式就不用一個個轉碼了
FileMover fileMover = new FileMover();//你也可以使用自帶的實例中jsp:useBean的形式
UploadBean upBean = new UploadBean();
MultipartFormDataRequest mrequest = null;
Hashtable files = null;

  if (MultipartFormDataRequestisMultipartFormData(request))
{
mrequest = new MultipartFormDataRequest(requestnull**MultipartFormDataRequestCOSPARSER"GBK");//注意這裡也要設置編碼參數
String sTt = mrequestgetParameter("title");
outprintln("<br>Title"+sTt+"<br>");
String sTt = new String(sTtgetBytes("ISO")"GBK");
outprintln("<br>Title"+sTt+"<br>");
//這裡用來測試title參數是否正確調試的時候加一句if (true)return;即可
files = mrequestgetFiles();
}

  
//獲取修改前的文件名
String sOldFileName =mrequestgetParameter("oldfilename");
outprintln("sOldFileName:"+sOldFileName);
String sWebRootPath = requestgetRealPath("/");//得到你的web應用的根
String sPath=sWebRootPath+"attach";
int iFileCount = ;
String sServerFileName="";
String sLocalFileName = "";
//文件獲取
if ( (files != null) || (!filesisEmpty()) ) {

  iFileCount = filessize();
UploadFile file = (UploadFile) filesget("attach");
sLocalFileName=filegetFileName();
outprintln("sLocalFileName:"+sLocalFileName);
int ii= sLocalFileNameindexOf(""); //取文件名的後綴
String sExt = sLocalFileNamesubstring(iisLocalFileNamelength());
//得到不重復的文件名
javautilDate dt = new javautilDate(SystemcurrentTimeMillis());
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
sServerFileName= fmtformat(dt);
sServerFileName =sServerFileName + sExt;
//如果不存在該目錄則新建一個
File dir =new File(sPath);
if (!direxists()){
dirmkdirs();
}
upBeansetFolderstore(sPath);//設置要上傳的目錄
upBeanaddUploadListener(fileMover);//增加filMover監聽
fileMoversetNewfilename(sServerFileName);//設置服務器上的文件名
upBeanstore(mrequest "attach");//上傳
outprintln("file path is "+sPath+"/"+sServerFileName);
}

  %>

  
Demo注意事項cosjaruploadbeanjarfilemoverjar這幾個包必須有
必備下載地址
UploadBean
FileMover
參考下載地址
ChinesUpload例子
參考了fbysss的一篇文章
orgapachestrutsuploadFormFile
Struts的orgapachestrutsuploadFormFile類很方便不用自己寫也不用寫一個jsp調用jspsmartupload就可以搞定

  
選擇上傳文件頁面selfilejsp

  

<%@ taglib uri="/WEBINF/strutshtmltld" prefix="html"%>
<html:html>
<html:form action="/uploadsActiondo" enctype="multipart/formdata">
<html:file property="theFile"/>
<html:submit/>
</html:form>
</html:html>

  
UpLoadActionjava

import javaio*;
import javaxservlet*;
import orgapachestrutsaction*;
import orgapachestrutsuploadFormFile;

  /** *//**
* <p>Title:UpLoadAction</p>
* <p>Description: QRRSMMS </p>
* <p>Copyright: Copyright (c) jiahansoft</p>
* <p>Company: jiahansoft</p>
* @author wanghw
* @version
*/

  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 = requestgetCharacterEncoding();
if ((encoding != null) && (encodingequalsIgnoreCase("utf")))
{
responsesetContentType("text/html; charset=gb");//如果沒有指定編碼編碼格式為gb
}
UpLoadForm theForm = (UpLoadForm ) form;
FormFile file = theFormgetTheFile();//取得上傳的文件
try {
InputStream stream = filegetInputStream();//把文件讀入
String filePath = requestgetRealPath("/");//取當前系統路徑
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + "/" +
filegetFileName());//建立一個上傳文件的輸出流
//Systemoutprintln(filePath+"/"+filegetFileName());
int bytesRead = ;
byte[] buffer = new byte[];
while ( (bytesRead = streamread(buffer )) != ) {
boswrite(buffer bytesRead);//將文件寫入服務器
}
bosclose();
streamclose();
}catch(Exception e){
Systemerrprint(e);
}
//requestsetAttribute("dat"filegetFileName());
return mappingfindForward("display");
}
return null;
}
}

  

  UpLoadFormjava

  

  
import javaxservlet
import orgapachestrutsaction*;
import orgapachestrutsupload*;

  /** *//**
* <p>Title:UpLoadForm</p>
* <p>Description: QRRSMMS </p>
* <p>Copyright: Copyright (c) jiahansoft</p>
* <p>Company: jiahansoft</p>
* @author wanghw
* @version
*/

  public class UpLoadForm extends ActionForm {
public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "orgapachestrutswebappuploadMaxLengthExceeded";
protected FormFile theFile;
public FormFile getTheFile() {
return theFile;
}
public void setTheFile(FormFile theFile) {
thistheFile = theFile;
}
public ActionErrors validate(ActionMapping mapping HttpServletRequest request)
{
ActionErrors errors = null;
//has the maximum length been exceeded?
Boolean maxLengthExceeded = (Boolean)
requestgetAttribute(MultipartRequestHandlerATTRIBUTE_MAX_LENGTH_EXCEEDED);
if ((maxLengthExceeded != null) && (maxLengthExceededbooleanValue()))
{
errors = new ActionErrors();
errorsadd(ERROR_PROPERTY_MAX_LENGTH_EXCEEDED new ActionError("maxLengthExceeded"));
}
return errors;

  }
}
//這是相對應的form還有其他屬性可以設置具體可以參考struts的上傳例子

  

  strutsconfigxml

  

  <?xml version="" encoding="UTF"?>
<!DOCTYPE strutsconfig PUBLIC "//Apache Software Foundation//DTD Struts Configuration //EN" "
<strutsconfig>
<formbeans>
<formbean name="uploadsForm" type="UpLoadForm" />
</formbeans>
<actionmappings>
<action name="uploadsForm" type="UpLoadAction" path="/uploadsAction">
<forward name="display" path="/displayjsp" />
</action>
</actionmappings>
</strutsconfig>
<!displayjsp就是隨便寫一個成功頁>


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20075.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.