java USES the component smartUpload to upload files based on servlet
- 2020-05-10 18:09:43
- OfStack
File upload is very common in web application. Now I will introduce file upload based on servlet. File upload based on Struts2 can be seen:
Page side code:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> registered </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="" class="box" id="login" />
<br/><br/>
<input type="file" name="file1" id="file"/>
<input type="submit" name="submit" value=" To complete the registration " />
</form>
</body>
</html>
The first thing to note here is that the form form with file upload must be wrapped as enctype="multipart/ form-data "; Here we interact directly with the background, without Ajax interaction, you need to use ajax can see: http: / / www cnblogs. com/shenliang123 category / 372520. html
Let's move on to 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 jsp The built-in object in servlet It can't be used directly, it needs to be done 1 Some processing
JspFactory _jspxFactory = null;
PageContext pageContext = null;
_jspxFactory = JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true);
smart.initialize(pageContext);// Initializes the upload operation
smart.upload();
IpTimeStamp its=new IpTimeStamp(InetAddress.getLocalHost().getHostAddress());//request.getRemoteAddr() Get the user's ip address
//System.out.println(" To obtain the ip for "+InetAddress.getLocalHost().getHostAddress());
// If you want to achieve bulk file upload, just use for Cycle, getFile(0) In the 0 Instead of i Can be
String ext=smart.getFiles().getFile(0).getFileExt();// This is the extension to get the file ,getFile(0) For only 1 the 1 Three uploaded files
String fileName=its.getIpTimeRand()+"."+ext;
//System.out.println(" To obtain File name "+fileName);
//this.getServletContext().getRealPath("/") To get tomcat Follow the directory and put it in upload In the folder, java.io.File.separator is 1 Seed safe operation
//String realPath="";
//this.getServletContext().getRealPath("/")+
smart.getFiles().getFile(0).saveAs("/headupload"+java.io.File.separator+fileName);
String realPath="headupload/"+fileName+"";
//
// Because of the preceding form The form has been encapsulated, so it's not easy to use here 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");// The user name
String email = smart.getRequest().getParameter("email");
PrintWriter out = response.getWriter();
// The following is the persistence layer operation, 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 avoid file name conflict, we will rename operations, here is a name to achieve IP+ timestamp:
Directly on the code, there is nothing to say, the implementation is still 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;// To get the 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("\\."); // It's broken down by points ip Address, but click to escape
for(int i=0;i<a.length;i++){
sbf.append(this.addZero(a[i], 3)); // Call the zeroing method, block ip insufficient 3 Bit auto-complement to 3 position
}
sbf.append(this.getTimeStamp()); // with this To call external methods
Random random=new Random(); // To generate a random number
for(int i=0;i<3;i++){ // produce 3 A random number
sbf.append(random.nextInt(10)); // Each random number does not exceed 10
}
}
return sbf.toString();
}
@SuppressWarnings("unused")
private String getDate(){ // Implementation of 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 zeroing method that takes the specified string and length
StringBuffer s=new StringBuffer();
s.append(str);
while(s.length()<len){
s.insert(0,"0"); // Zeroing is performed at the zero position
}
return s.toString();
}
// Do the test
public static void main(String [] ary){
IpTimeStamp IpTimeStamp=new IpTimeStamp("172.168.3.222");// Calls the constructor with a parameter
System.out.println(IpTimeStamp.getIpTimeRand());
}
}