jsp

位置:IT落伍者 >> jsp >> 浏览文章

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


发布日期:2018年09月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就是随便写一个成功页>

               

上一篇:JSP页面中的精确到秒的时间控件

下一篇:JSP动态网站环境搭建应用中的详细步骤