加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 教程 > 正文

JSP实现上传文件的两种方法介绍

发布时间:2023-05-15 14:54:12 所属栏目:教程 来源:
导读:在用java开发企业器系统的使用,特别是涉及到与办公相关的软件开发的时候,文件的上传是客户经常要提到的要求.因此有 一套很好文件上传的解决办法也能方便大家在这一块的开发.

首先申明,该文章是为了自己记录一备以
在用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开发资料库,
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!