java基于servlet使用组件smartUpload实现文件上传
文件上传在web应用中是非常常见的,现在我就介绍下基于servlet的文件上传,基于Struts2的文件上传可以看:
页面端代码:
<%@pagelanguage="java"import="java.util.*"pageEncoding="GBK"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <title>注册</title> </head> <body> <formname="form1"onsubmit="returnon_submit()" action="RegisterServlet"method="post"enctype="multipart/form-data"> <inputtype="text"name="uname1"id="password"/> <inputtype="text"name="uname2"id="uname2"/> <inputtype="password"name="password1"id="password"/> <inputtype="password"name="password2"id="password"/> <inputtype="radio"value="男"checked="checked"name="sex"/>男 <inputtype="radio"value="女"name="sex"/>女 <inputtype="text"name="email"value=""class="box"id="login"/> <br/><br/> <inputtype="file"name="file1"id="file"/> <inputtype="submit"name="submit"value="完成注册"/> </form> </body> </html>
这里要注意的一点就是存在文件上传的form表单必须封装为enctype="multipart/form-data";这里我们直接与后台进行交互,不进行Ajax交互,需要使用ajax可以看:http://www.cnblogs.com/shenliang123/category/372520.html
下面我们继续来看servlet的代码实现:
packagecom.xidian.bbs.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.net.InetAddress;
importjava.sql.Connection;
importjava.sql.ResultSet;
importjava.sql.Statement;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.jsp.JspFactory;
importjavax.servlet.jsp.PageContext;
importcom.jspsmart.upload.*;
importcom.xidian.bbs.bean.Bean;
importcom.xidian.bbs.bean.RegisterBean;
importcom.xidian.bbs.util.DBAccess;
importcom.xidian.bbs.util.IpTimeStamp;
@SuppressWarnings("serial")
publicclassRegisterServletextendsHttpServlet{
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("GBK");
SmartUploadsmart=newSmartUpload();
try{
//PageContext是jsp的内置对象,在servlet不能直接使用,需要做一些处理
JspFactory_jspxFactory=null;
PageContextpageContext=null;
_jspxFactory=JspFactory.getDefaultFactory();
pageContext=_jspxFactory.getPageContext(this,request,response,"",true,8192,true);
smart.initialize(pageContext);//初始化上传操作
smart.upload();
IpTimeStampits=newIpTimeStamp(InetAddress.getLocalHost().getHostAddress());//request.getRemoteAddr()获得用户的ip地址
//System.out.println("获取的ip为"+InetAddress.getLocalHost().getHostAddress());
//如果要实现文件的批量上传,则只需用for循环,将getFile(0)中的0改为i即可
Stringext=smart.getFiles().getFile(0).getFileExt();//此为得到文件的扩展名,getFile(0)为得到唯一的一个上传文件
StringfileName=its.getIpTimeRand()+"."+ext;
//System.out.println("获取的文件名为"+fileName);
//this.getServletContext().getRealPath("/")为得到tomcat的跟目录,放于upload文件夹中,java.io.File.separator是一种安全操作
//StringrealPath="";
//this.getServletContext().getRealPath("/")+
smart.getFiles().getFile(0).saveAs("/headupload"+java.io.File.separator+fileName);
StringrealPath="headupload/"+fileName+"";
//
//由于前面的form表单已经进行了封装,这里就不能简单的用request.getparameter()来获取表单参数
Stringuname1=smart.getRequest().getParameter("uname1");//昵称
Stringupass1=smart.getRequest().getParameter("password1");
Stringsex=smart.getRequest().getParameter("sex");
Stringuname2=smart.getRequest().getParameter("uname2");//用户名
Stringemail=smart.getRequest().getParameter("email");
PrintWriterout=response.getWriter();
//以下是持久层操作,省略。。。。。。。。。。
}
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
}
上面使用到的ip+时间戳的类IpTimeStamp对文件进行重命名:
在上传文件等操作中,我们为了不让文件名冲突,都会进行重命名操作,这里就介绍一个实现IP+时间戳的命名:
直接上代码了,也没什么好说的,实现还是挺简单的,不过实用
packagecom.xidian.bbs.util;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Random;
publicclassIpTimeStamp{
privateSimpleDateFormatsim=null;//用来获取时间
privateStringip=null;
publicIpTimeStamp(){
}
publicIpTimeStamp(Stringip){
this.ip=ip;
}
publicStringgetIpTimeRand(){
StringBuffersbf=newStringBuffer();
if(this.ip!=null){
Stringa[]=this.ip.split("\\.");//根据点来拆分ip地址,但点要转义
for(inti=0;i<a.length;i++){
sbf.append(this.addZero(a[i],3));//调用补零的方法,每块ip不足三位的自动补足到三位
}
sbf.append(this.getTimeStamp());//用this来调用外部的方法
Randomrandom=newRandom();//要产生随机数
for(inti=0;i<3;i++){//产生三位随机数
sbf.append(random.nextInt(10));//每位随机数都不超过10
}
}
returnsbf.toString();
}
@SuppressWarnings("unused")
privateStringgetDate(){//关于日期与时间的实现
this.sim=newSimpleDateFormat("yyyy-mm-ddhh:mm:ss.SSS");
returnthis.sim.format(newDate());
}
privateStringgetTimeStamp(){//返回时间戳
this.sim=newSimpleDateFormat("yyyymmddhhmmssSSS");
returnthis.sim.format(newDate());
}
privateStringaddZero(Stringstr,intlen){//自动补零的方法,参数为指定的字符串和长度
StringBuffers=newStringBuffer();
s.append(str);
while(s.length()<len){
s.insert(0,"0");//在零的位置上进行补零操作
}
returns.toString();
}
//做测试
publicstaticvoidmain(String[]ary){
IpTimeStampIpTimeStamp=newIpTimeStamp("172.168.3.222");//调用有参数的构造方法
System.out.println(IpTimeStamp.getIpTimeRand());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。