当前位置: 移动技术网 > IT编程>开发语言>Java > java基于servlet使用组件smartUpload实现文件上传

java基于servlet使用组件smartUpload实现文件上传

2019年07月22日  | 移动技术网IT编程  | 我要评论

浙江人事,手淫技巧,超次元偶像王嘉尔

文件上传在web应用中是非常常见的,现在我就介绍下基于servlet的文件上传,基于struts2的文件上传可以看:

页面端代码:

<%@ page language="java" import="java.util.*" pageencoding="gbk"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>注册</title>
</head>
<body>
   <form name="form1" onsubmit="return on_submit()"
    action="registerservlet" method="post" enctype="multipart/form-data">
         <input type="text" name="uname1" id="password" />
         <input type="text" name="uname2" id="uname2"/>
         <input type="password" name="password1" id="password" />
         <input type="password" name="password2" id="password"/>
         <input type="radio" value="男" checked="checked" name="sex"/>男 
                    
         <input type="radio" value="女" name="sex"/>女
         <input type="text" name="email" value="" class="box" id="login" />
         <br/><br/>
         <input type="file" name="file1" id="file"/>
      <input type="submit" name="submit" value="完成注册" />
   </form>
</body>
</html>

这里要注意的一点就是存在文件上传的form表单必须封装为enctype="multipart/form-data";这里我们直接与后台进行交互,不进行ajax交互,需要使用ajax可以看:

下面我们继续来看servlet的代码实现:

package com.xidian.bbs.servlet;

import java.io.ioexception;
import java.io.printwriter;
import java.net.inetaddress;
import java.sql.connection;
import java.sql.resultset;
import java.sql.statement;

import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.jsp.jspfactory;
import javax.servlet.jsp.pagecontext;

import com.jspsmart.upload.*;
import com.xidian.bbs.bean.bean;
import com.xidian.bbs.bean.registerbean;
import com.xidian.bbs.util.dbaccess;
import com.xidian.bbs.util.iptimestamp;

@suppresswarnings("serial")
public class registerservlet extends httpservlet{
 protected void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  response.setcontenttype("text/html");
  response.setcharacterencoding("gbk");
  request.setcharacterencoding("gbk");
  
  smartupload smart=new smartupload();
  try{
  //pagecontext是jsp的内置对象,在servlet不能直接使用,需要做一些处理
  jspfactory _jspxfactory = null;
   pagecontext pagecontext = null;
   _jspxfactory = jspfactory.getdefaultfactory();
   pagecontext = _jspxfactory.getpagecontext(this,request,response,"",true,8192,true);

  smart.initialize(pagecontext);//初始化上传操作
  smart.upload();
  iptimestamp its=new iptimestamp(inetaddress.getlocalhost().gethostaddress());//request.getremoteaddr()获得用户的ip地址
  //system.out.println("获取的ip为"+inetaddress.getlocalhost().gethostaddress());
  //如果要实现文件的批量上传,则只需用for循环,将getfile(0)中的0改为i即可
  string ext=smart.getfiles().getfile(0).getfileext();//此为得到文件的扩展名,getfile(0)为得到唯一的一个上传文件
  string filename=its.getiptimerand()+"."+ext;
  //system.out.println("获取 的文件名为"+filename);
  //this.getservletcontext().getrealpath("/")为得到tomcat的跟目录,放于upload文件夹中,java.io.file.separator是一种安全操作
  //string realpath="";
  //this.getservletcontext().getrealpath("/")+
  smart.getfiles().getfile(0).saveas("/headupload"+java.io.file.separator+filename);
  string realpath="headupload/"+filename+"";
  
  //
  //由于前面的form表单已经进行了封装,这里就不能简单的用request.getparameter()来获取表单参数
  string uname1 = smart.getrequest().getparameter("uname1");//昵称
  string upass1 = smart.getrequest().getparameter("password1");
  string sex = smart.getrequest().getparameter("sex");
  string uname2 = smart.getrequest().getparameter("uname2");//用户名
  string email = smart.getrequest().getparameter("email");
  printwriter out = response.getwriter();
 
     //以下是持久层操作,省略。。。。。。。。。。
 }
 protected void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
   doget(request,response);
 }

}

上面使用到的ip+时间戳的类iptimestamp对文件进行重命名:

在上传文件等操作中,我们为了不让文件名冲突,都会进行重命名操作,这里就介绍一个实现ip+时间戳的命名:

直接上代码了,也没什么好说的,实现还是挺简单的,不过实用

package com.xidian.bbs.util;

import java.text.simpledateformat;
import java.util.date;
import java.util.random;

public class iptimestamp {
 private simpledateformat sim=null;//用来获取时间
 private string ip=null;
 public iptimestamp(){
 }
 public iptimestamp(string ip){
  this.ip=ip;
 }
 public string getiptimerand(){
  stringbuffer sbf=new stringbuffer();
  if(this.ip!=null){
   string a[]=this.ip.split("\\.");    //根据点来拆分ip地址,但点要转义
   for(int i=0;i<a.length;i++){
    sbf.append(this.addzero(a[i], 3));   //调用补零的方法,每块ip不足三位的自动补足到三位
   }
   sbf.append(this.gettimestamp());    //用this来调用外部的方法
   random random=new random();      //要产生随机数
   for(int i=0;i<3;i++){       //产生三位随机数
    sbf.append(random.nextint(10));    //每位随机数都不超过10
   }
  }
  return sbf.tostring();
 }
 @suppresswarnings("unused")
 private string getdate(){        //关于日期与时间的实现
  this.sim=new simpledateformat("yyyy-mm-dd hh:mm:ss.sss");
  return this.sim.format(new date());
 }
 private string gettimestamp(){       //返回时间戳
  this.sim=new simpledateformat("yyyymmddhhmmsssss");
  return this.sim.format(new date());
 }
 private string addzero(string str,int len){    //自动补零的方法,参数为指定的字符串和长度
  stringbuffer s=new stringbuffer();
  s.append(str);
  while(s.length()<len){
   s.insert(0,"0");        //在零的位置上进行补零操作
  }
  return s.tostring();
 }
 
 //做测试
 public static void main(string [] ary){
  iptimestamp iptimestamp=new iptimestamp("172.168.3.222");//调用有参数的构造方法
  system.out.println(iptimestamp.getiptimerand());
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网