java USES common fileupload to upload files

  • 2020-05-10 18:09:49
  • OfStack

The function of the file upload is a very common site, direct use of Servlet for uploading files have to parse the request parameters, more troublesome, so 1 choice USES apache open source tools, common - fileupload. This jar bag can again apache found on the website, also can be found under the struts lib folder, struts upload function is based on the implementation.

common-fileupload relies on the common-io package, so you will need to download this package as well. Then import it under your project path.

The usage code is as follows


package oop.hg.ytu.servlet; 
 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.List; 
 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import oop.hu.ytu.dao.UploadDomain; 
 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
 
public class Upload extends HttpServlet { 
 
  /** 
   *  Handle user upload requests  
   */ 
  private static final long serialVersionUID = 1L; 
 
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
  // String describe = request.getParameter("describe"); 
    DiskFileItemFactory factory = new DiskFileItemFactory(); 
    @SuppressWarnings("deprecation") 
    String path = request.getRealPath("/upload");// Set the disk buffer path  
   
    factory.setRepository(new File(path)); 
    factory.setSizeThreshold(1024*1024);// Set the create buffer size  
     
    ServletFileUpload upload = new ServletFileUpload(factory); 
    upload.setSizeMax(-1);// Set the upload file size limit ,-1 There is no upper limit  
    try { 
      @SuppressWarnings("unchecked") 
      List<FileItem> list = upload.parseRequest(request); 
      String va = null; 
      for(FileItem item : list){ 
    //   String name = item.getFieldName(); 
        if(item.isFormField()){// Determine if it is a file stream  
           
          va = item.getString("UTF-8"); 
        // System.out.println(name+"="+va); 
      ///   request.setAttribute(name, value); 
        }else{ 
          String value = item.getName();// It will pass the full pathname  
          int start = value.lastIndexOf("\\"); 
          String fileName = value.substring(start+1); 
      //   request.setAttribute(name, fileName); 
          InputStream in = item.getInputStream(); 
          UploadDomain dao = new UploadDomain(); 
          //item.write(new File(realPath,fileName)); 
          int index = fileName.lastIndexOf("."); 
          String realFileName = fileName.substring(0,index); 
          String type = fileName.substring(index+1); 
          dao.insert(in, realFileName,type,va);// Put it into the database  
           
        } 
      } 
    } catch (Exception e) { 
       
      e.printStackTrace(); 
    } 
  } 
 
  public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    doGet(request, response); 
 
  } 
 
}

  determines whether it is an uploaded stream or a parameter in the form, such as a text box that submits information and inserts it into the database. Database insert
The following code


package oop.hu.ytu.dao; 
 
import java.io.InputStream; 
import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
 
import oop.hg.ytu.utils.JdbcUtils; 
 
/** 
 *  File upload support is available  
 * @author Administrator 
 * 
 */ 
public class UploadDomain { 
  /** 
   *  Exiles the uploaded file into the database  
   */ 
  public void insert(InputStream in, String fileName, String type,String describe) throws Exception{// Write the image to the database   
    Connection conn = null;  
    PreparedStatement ps = null;  
    ResultSet rs = null;  
    System.out.println(describe); 
    try {  
      // 2. Establish a connection   
      conn = JdbcUtils.getConnection(); 
      // 3. Create statements   
      String sql = "insert into fileupload(file,filename,type,des) values (?,?,?,?)";  
      ps = conn.prepareStatement(sql);  
      ps.setBlob(1, in); 
      ps.setString(2, fileName); 
      ps.setString(3, type); 
      ps.setString(4, describe); 
      // 4. Execute the statement   
      ps.executeUpdate();  
  
      in.close();  
  
      
    } finally {  
      JdbcUtils.free(rs, ps, conn);  
    }  
  }  
} 

You may encounter the database default query size limit and need to change the following configuration under my.ini under the mysql installation directory,
[mysqld]  
max_allowed_packet=64M  

That's it. Of course, pay attention to the encoding. Upload the file. Also, one of my column names is set to describe, and the result is reserved with Mysql
Suddenly, there is no way to insert information phenomenon, after 1 must pay attention to.


Related articles: