JSP上传文件代码.docx
- 文档编号:9148459
- 上传时间:2023-02-03
- 格式:DOCX
- 页数:6
- 大小:16.40KB
JSP上传文件代码.docx
《JSP上传文件代码.docx》由会员分享,可在线阅读,更多相关《JSP上传文件代码.docx(6页珍藏版)》请在冰豆网上搜索。
JSP上传文件代码
UploadExample.jsp
<%@pagecontentType="text/html;charset=gb2312"%>
上传文件程序应用示例
<%-- 类型enctype用multipart/form-data,这样可以把文件中的数据作为流式数据上传,不管是什么文件类型,均可上传。
--%>
请选择要上传的文件
来源:
(-用JSP实现文件上传功能_chuansir_新浪博客
doUpload.jsp
<%@pagecontentType="text/html;charset=GBK"%>
<%@pageimport="java.io.*"%>
<%@pageimport="java.util.*"%>
<%@pageimport="javax.servlet.*"%>
<%@pageimport="javax.servlet.http.*"%>
<%
//定义上载文件的最大字节
intMAX_SIZE=102400*102400;
//创建根路径的保存变量
StringrootPath;
//声明文件读入类
DataInputStreamin=null;
FileOutputStreamfileOut=null;
//取得客户端的网络地址
StringremoteAddr=request.getRemoteAddr();
//获得服务器的名字
StringserverName=request.getServerName();
//取得互联网程序的绝对地址
StringrealPath=request.getRealPath(serverName);
realPath=realPath.substring(0,realPath.lastIndexOf("\\"));
//创建文件的保存目录
rootPath=realPath+"\\upload\\";
//取得客户端上传的数据类型
StringcontentType=request.getContentType();
try{
if(contentType.indexOf("multipart/form-data")>=0){
//读入上传的数据
in=newDataInputStream(request.getInputStream());
intformDataLength=request.getContentLength();
if(formDataLength>MAX_SIZE){
out.println("
上传的文件字节数不可以超过"+MAX_SIZE+"
");return;
}
//保存上传文件的数据
bytedataBytes[]=newbyte[formDataLength];
intbyteRead=0;
inttotalBytesRead=0;
//上传的数据保存在byte数组
while(totalBytesRead byteRead=in.read(dataBytes,totalBytesRead,formDataLength); totalBytesRead+=byteRead; } //根据byte数组创建字符串 Stringfile=newString(dataBytes); //out.println(file); //取得上传的数据的文件名 StringsaveFile=file.substring(file.indexOf("filename=\"")+10); saveFile=saveFile.substring(0,saveFile.indexOf("\n")); saveFile=saveFile.substring(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\"")); intlastIndex=contentType.lastIndexOf("="); //取得数据的分隔字符串 Stringboundary=contentType.substring(lastIndex+1,contentType.length()); //创建保存路径的文件名 StringfileName=rootPath+saveFile; //out.print(fileName); intpos; pos=file.indexOf("filename=\""); pos=file.indexOf("\n",pos)+1; pos=file.indexOf("\n",pos)+1; pos=file.indexOf("\n",pos)+1; intboundaryLocation=file.indexOf(boundary,pos)-4; //out.println(boundaryLocation); //取得文件数据的开始的位置 intstartPos=((file.substring(0,pos)).getBytes()).length; //out.println(startPos); //取得文件数据的结束的位置 intendPos=((file.substring(0,boundaryLocation)).getBytes()).length; //out.println(endPos); //检查上载文件是否存在 FilecheckFile=newFile(fileName); if(checkFile.exists()){ out.println(" "+saveFile+"文件已经存在.
}
//检查上载文件的目录是否存在
FilefileDir=newFile(rootPath);
if(!
fileDir.exists()){
fileDir.mkdirs();
}
//创建文件的写出类
fileOut=newFileOutputStream(fileName);
//保存文件的数据
fileOut.write(dataBytes,startPos,(endPos-startPos));
fileOut.close();
out.println(saveFile+"文件成功上载.
");}else{
Stringcontent=request.getContentType();
out.println("
上传的数据类型不是multipart/form-data
");}
}catch(Exceptionex){
thrownewServletException(ex.getMessage());
}
%>