File upload learning record used in Java Web project (1)

Keywords: Java SQL Apache JSP

File upload learning record used in Java Web project (1)


Introduction:

File upload is a commonly used function in development. I will mainly introduce the implementation of basic file upload function with commons-fileupload-1.2.1.jar package, that is, file upload to the specified directory, and introduce the relevant classes and methods used in the upload process.

Download plug-ins
jar package to prepare:
*Commons-fileupload-1.2.1.jar (must be imported)
*Commons-io-1.4.jar (must be imported. If the project is not imported, the program will not report an error at compile time, but it will report an error at run time after release)

Development environment:
jdk 1.8 tomcat 8


package com.schoolmates.admin.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.mysql.jdbc.Connection;
import com.schoolmates.model.SchoolmateMien;
import com.schoolmates.model.SchoolmatePublish;
import com.schoolmates.util.SqlConnectionUtil;

/**
 * SchoolmatePublishSetHeadImageController(Set the head image of alumni Journal)
 * @author Guozhu Zhu
 * @date 2017/12/24
 * @version 1.0
 *
 */
public class SchoolmatePublishSetHeadImageController extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public Connection conn = null;
	
    public java.sql.PreparedStatement ps = null;
    
    public java.sql.ResultSet rs = null;
    
    public int rs1;
    
    public SqlConnectionUtil sqlUtil = null;
    
    public SchoolmatePublish news = null;
    
    // Define constant, save file path
    private static final String FILE_PATH = "F:" + File.separator + "schoolmates"
                + File.separator + "upload" + File.separator;// Path of file upload
    
    private static final String FILE_TEMP = "F:" + File.separator + "schoolmates"
                + File.separator + "temp" + File.separator;;// File cache path

    // Upload configuration
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
	}
	
	/**
     * Upload data and save files
     */
    protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    	 PrintWriter writer;
    	// Check whether it is multimedia upload
        if (!ServletFileUpload.isMultipartContent(request)) {
            // Stop if not
            writer = response.getWriter();
            writer.println("Error: Form must contain enctype=multipart/form-data");
            writer.flush();
            return;
        }

        // Configure upload parameters
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Set memory threshold - when exceeded, temporary files will be generated and stored in the temporary directory
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // Set temporary storage directory
        File fileTemp = new File(FILE_TEMP);
        if (!fileTemp.exists()){
          fileTemp.mkdirs();
        }
        
        File localDir = new File(FILE_PATH);
        if (!localDir.exists()) {
             localDir.mkdir();
        }
        
        factory.setRepository(fileTemp);
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // Set the maximum file upload value
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // Set the maximum request value (including file and form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        // Chinese processing
        upload.setHeaderEncoding("UTF-8"); 

        try {
            // Parsing the requested content extraction file data
            List<FileItem> formItems = upload.parseRequest(request);
            String filePath = null;
            String value = null;
            String fileName = null;
            //Generate a universal unique ID
            String uuid = UUID.randomUUID().toString(); 
            String uniqueId = uuid.replaceAll("-", "");
            String localFilePath = null;
            if (formItems != null && formItems.size() > 0) {
                // Data of overlapping representative list
                for (FileItem item : formItems) {
                    // Processing fields that are not in the form (that is, processing files)
                    if (!item.isFormField()) {
                        fileName = new File(item.getName()).getName();
                        fileName = uniqueId+fileName;
                        filePath = FILE_PATH + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // Upload path of output file in console
                        System.out.println(filePath);
                        // Save files to hard disk
                        item.write(storeFile);
                    } else {
                    	  String name = item.getFieldName();
                          //To solve the problem of Chinese scrambling for data of common input items
                          value = item.getString("UTF-8");
                          //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                          System.out.println(name + "=" + value);
                          
                    }
                }
                   
                        
                        news = new SchoolmatePublish();
                        news.setHead_image(fileName);
                        news.setId(Integer.parseInt(value));
                    	   try {
                            	SqlConnectionUtil.init();
                                conn = SqlConnectionUtil.getConnection();
                                String sql="update schoolmate_publish set head_image='"+news.getHead_image()+"' where id="+news.getId();
                                ps=conn.prepareStatement(sql);
                                rs1=ps.executeUpdate();
                                if (rs1 == 0) {
                                	request.setAttribute("message",
                                            "File upload failed!");
                                } else {
                                	request.setAttribute("message",
                                            "File uploaded successfully!");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }finally{
                                if(conn !=null){
                                    try {
                                        conn.close();
                                    } catch (Exception e2) {
                                        e2.printStackTrace();
                                    }
                                }
                                if(ps !=null){
                                    try {
                                        ps.close();
                                    } catch (Exception e2) {
                                        e2.printStackTrace();
                                    }
                                }
                            }
                       
                    }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "error message: " + ex.getMessage());
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher("/message.jsp");
		dispatcher.forward(request, response);
    }
    
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String page = request.getParameter("page") == null ? "1" : request.getParameter("page");
		Integer p = (Integer.parseInt(page)-1);
		//Start index location
		Integer start = (p*10);
        try {
        	SqlConnectionUtil.init();
            conn = SqlConnectionUtil.getConnection();
            String sql="select*from schoolmate_publish where id="+request.getParameter("id");
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
            List<SchoolmatePublish> newslist= new ArrayList<SchoolmatePublish>();
            SchoolmatePublish news=null;
            while(rs.next()){
                news=new  SchoolmatePublish();
                news.setId(rs.getInt("id"));
                newslist.add(news);
            }
            request.setAttribute("newslist", newslist);
            request.setAttribute("page", p+1);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(conn !=null){
                try {
                    conn.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            if(ps !=null){
                try {
                    ps.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            if(rs !=null){
                try {
                    rs.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
		RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/Admin/SchoolmatePublish/setHeadImage.jsp");
		dispatcher.forward(request, response);
	}

}





Original link address: Click to open the link








Posted by hypuk on Sun, 03 May 2020 02:26:04 -0700