JSP實現上傳文件的兩種方法
2024-09-05 00:20:25
供稿:網友
在用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:[email protected]
//==========================================================================
-->
<%@ 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就是隨便寫一個成功頁-->
注冊會員,創建你的web開發資料庫,