Java based servlet uses component Smartupload to implement file uploads _java

Source: Internet
Author: User

File uploads are very common in web apps, and now I'm going to introduce a servlet based file upload, which can be seen based on Struts2 file uploads:

Page End Code:

<%@ page language= "java" import= "java.util.*" pageencoding= "GBK"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

The point to note here is that there is a form of file upload must be encapsulated as enctype= "Multipart/form-data", where we interact directly with the background, without Ajax interaction, need to use Ajax to see: http:// Www.cnblogs.com/shenliang123/category/372520.html

Let's go on to see the code implementation of the 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 is the built-in object of JSP, in the servlet cannot be used directly, need to do some processing jspfactory _jspxfactory = null;
   PageContext pagecontext = null;
   _jspxfactory = Jspfactory.getdefaultfactory ();

  PageContext = _jspxfactory.getpagecontext (This,request,response, "", true,8192,true);
  Smart.initialize (PageContext);//initialization upload operation Smart.upload (); Iptimestamp its=new Iptimestamp (Inetaddress.getlocalhost (). gethostaddress ());//request.getremoteaddr () Obtain the user's IP address/
  /SYSTEM.OUT.PRINTLN ("Obtained IP is" +inetaddress.getlocalhost (). gethostaddress ()); If you want to implement a bulk upload of a file, simply use the For loop to change 0 in GetFile (0) to I to String ext=smart.getfiles (). GetFile (0). Getfileext ()//This is the file extension. GetFile (0) to get the only one upload file String filename=its.getiptimerand () + "."
  +ext;
  SYSTEM.OUT.PRINTLN ("Obtained file name is" +filename); This.getservletcontext (). Getrealpath ("/") to get Tomcat's directory, put it in the upload folder, Java.io.File.separator is a safe operation//string
  Realpath= ""; This.getservletcontext (). Getrealpath ("/") + Smart.getfiles (). GetFile (0). SaveAs ("/headupload" +
  Java.io.file.separator+filename); StrinG realpath= "headupload/" +filename+ ""; Since the previous form form has already been encapsulated, it is not easy to use Request.getparameter () to get the form parameter String uname1 = Smart.getrequest (). GetParameter ("
  Uname1 ");//nickname String Upass1 = Smart.getrequest (). GetParameter (" Password1 ");
  String sex = Smart.getrequest (). GetParameter ("Sex"); String uname2 = Smart.getrequest (). GetParameter ("uname2");//username string email = smart.getrequest (). GetParameter ("email
  ");
 
     PrintWriter out = Response.getwriter ();
 The following is the persistence layer operation, omitting ...  } protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException
 {doget (request,response);

 }

}

The ip+ timestamp class used above Iptimestamp renames the file:

In the upload file and other operations, we do not let the filename conflict, will be renamed operations, here is a implementation of the ip+ timestamp name:

Directly on the code, there is nothing to say, the implementation is quite simple, but practical

Package com.xidian.bbs.util;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;

Import Java.util.Random;
 The public class Iptimestamp {private SimpleDateFormat sim=null;//is used to get time 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 ("\.");   Splits the IP address according to the point, but the point is to escape for (int i=0;i<a.length;i++) {sbf.append (This.addzero (A[i), 3));    Call the method of zeroing, each block of IP less than three bits of automatic replenishment to three-bit} sbf.append (This.gettimestamp ());      Use this to invoke an external method Random random=new Random ();    To generate a random number for (int i=0;i<3;i++) {//Generate three-bit random number sbf.append (Random.nextint (10));
 Each random number is no more than ten} return sbf.tostring (); @SuppressWarnings ("unused") private String getDate () {//about the implementation of the date and time This.sim=new SimpleDateFormat ("Yyyy-mm-dd Hh:mm:ss.
  SSS ");
 Return This.sim.format (New Date ()); Private String Gettimestamp () {//return timestamp
  This.sim=new SimpleDateFormat ("yyyymmddhhmmsssss");
 Return This.sim.format (New Date ());
  private string Addzero (string Str,int len) {//automatic zero-complement method, parameter is the specified string and length StringBuffer s=new stringbuffer ();
  S.append (str);        while (S.length () <len) {s.insert (0, "0");
 0 operation at zero position} return s.tostring (); ///Do test public static void Main (String [] ary) {iptimestamp iptimestamp=new iptimestamp ("172.168.3.222");//Call constructor with arguments
 FA System.out.println (Iptimestamp.getiptimerand ());
 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.