File upload is very common in web applications. Now I will introduce file upload based on servlet. File upload based on Struts2 can be viewed:
Page side code:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Register</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="male" checked="checked" name="sex"/> Male<input type="radio" value="female" name="sex"/> Female<input type="text" name="email" value="" id="login" /> <br/><br/> <input type="file" name="file1" id="file"/> <input type="submit" name="submit" value="Complete Registration" /> </form></body></html>
One thing to note here is that the form form uploaded by the file must be enctype="multipart/form-data"; here we interact directly with the background without Ajax interaction. If you need to use ajax, you can see: http://www.cnblogs.com/shenliang123/category/372520.html
Let's continue to look at the code implementation of 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 a built-in object of jsp. It cannot be used directly in servlet, and some processing is needed. JspFactory _jspxFactory = null; PageContext pageContext = null; _jspxFactory = JspFactory.getDefaultFactory(); pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true); smart.initialize(pageContext);//Initialize the upload operation smart.upload(); IpTimeStamp its=new IpTimeStamp(InetAddress.getLocalHost().getHostAddress());//request.getRemoteAddr() gets the user's ip address//System.out.println("The ip is obtained is"+InetAddress.getLocalHost().getHostAddress()); //If you want to implement batch upload of files, you just need to use a for loop and change 0 in getFile(0) to i to String ext=smart.getFiles().getFile(0).getFileExt();//This is the extension to get the file, getFile(0) is the only upload file String fileName=its.getIpTimeRand()+"."+ext; //System.out.println("The file name obtained is "+fileName); //this.getServletContext().getRealPath("/") To obtain the tomcat directory, it is placed 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 been encapsulated, we cannot simply use request.getparameter() to get the form parameters 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 are persistence layer operations, omitted. . . . . . . . . . } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }}The ip+timestamp class IpTimeStamp used above renames the file:
In uploading files and other operations, in order to prevent file names from conflicting, we will perform renaming operations. Here is a naming that implements IP+ timestamps:
I just uploaded 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;public class IpTimeStamp { private SimpleDateFormat sim=null;//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("//."); //Split the ip address according to the point, but the point must be escaped for(int i=0;i<a.length;i++){ sbf.append(this.addZero(a[i], 3)); //Calling the zero-complement method, and each ip with less than three digits is automatically supplemented to three digits} sbf.append(this.getTimeStamp()); //Use this to call the external method Random random=new Random(); //Creating a random number for(int i=0;i<3;i++){ //Creating three-digit random number sbf.append(random.nextInt(10)); //Each random number does not exceed 10 } } return sbf.toString(); } @SuppressWarnings("unused") private String getDate(){ //Regarding 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){ //The automatic zero-complement method, the parameters are the specified string and length StringBuffer s=new StringBuffer(); s.append(str); while(s.length()<len){ s.insert(0,"0"); //Complete zero-complement operation at the zero position} return s.toString(); } //Test public static void main(String [] ary){ IpTimeStamp IpTimeStamp=new IpTimeStamp("172.168.3.222"); //Calling the constructor with parameters System.out.println(IpTimeStamp.getIpTimeRand()); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.