Category:Java相关问题解决方案
Article From:https://www.cnblogs.com/charlypage/p/9064941.html

1.File upload -servlet to achieve file upload — core API – DiskFileItemFactory

1. Summary of file uploading

l  To achieve the file upload function in web development, we need to complete the following two steps:

•    Add the upload entry to the web page

•    Read the uploaded file data in servlet and save it to the local hard disk.

l  How do you add an upload entry to a web page?

•    <input type=“file”>Tags are used to add file upload entries to web pages.

•    1、You must set the name attribute of the input entry, otherwise the browser will not send the data uploaded to the file.

•    2、After setting the value of the form’s enctype value to multipart/form-data., when the browser uploads the file, the file data will be attached to the body of the HTTP request message and the MIME protocol is used to describe the uploaded files for convenience.The uploaded data are parsed and processed.

l  How to read files uploaded in Servlet and save them to the local hard disk?

•    RequestThe object provides a getInputStream method, which can read the data submitted by the client. However, because users may upload multiple files at the same time, it is not a good thing to read and upload data directly on the servlet side, and parse the corresponding file data separately.Often troublesome work, example.

•    To facilitate user processing of file uploads, the Apache open source organization provides an open source component (Commons-fileupload) for processing form file uploads, which has excellent performance and its API is very simple to make developers easy.Now web file upload function, so in web development to achieve file upload function, usually using Commons-fileupload components to achieve.

l  Using Commons-fileupload components to upload files, you need to import the corresponding supporting jar packages of the component: Commons-fileupload and commons-io. Commons-io does not belong to the development of the file upload component jThe AR file, but the Commons-fileupload component starts with version 1.1, and it needs the support of the commons-io package when it works.

Two. Core API – DiskFileItemFactory

l  DiskFileItemFactory It is a factory that creates FileItem objects.

•    public void setSizeThreshold(int sizeThreshold) :Set the size of the memory buffer, with a default value of 10K. When the uploaded file is larger than the buffer,fileuploadThe component will use the temporary file cache to upload the file.

•    public void setRepository(java.io.File repository) :Specify temporary file directory with default value of System.getProperty (“java.io.tmpdir”).

•    public DiskFileItemFactory(int sizeThreshold,java.io.File repository) :Constructor

l  ServletFileUpload Responsible for handling uploaded file data and encapsulating each entry in the form into a FileItem object. The common methods are:

•    boolean isMultipartContent(HttpServletRequest request) :Determine whether the upload form is multipart/form-data type.

•    List parseRequest(HttpServletRequest request):Parse the request object and wrap each entry in the form into a fileItem object and return a list collection that holds all FileItem.

•    setFileSizeMax(long fileSizeMax) :Setting up the maximum value of the uploaded file

•    setSizeMax(long sizeMax) :Set the maximum amount of uploaded files

•    setHeaderEncoding(java.lang.String encoding) :Setting the encoding format

•    setProgressListener(ProgressListener pListener)

Three file upload case

l  Implementation steps

1、Create DiskFileItemFactory object, set buffer size and temporary file directory

2、Use the DiskFileItemFactory object to create the ServletFileUpload object and set the size limit for uploading files.

3、Call the ServletFileUpload.parseRequest method to parse the request object and get a List object that holds all uploaded content.

4、Iterate over list, iterate over a FileItem object, and call its isFormField method to determine whether it is an uploaded file.

•    For the normal form field, the getFieldName and getString methods are called to get the field name and field values.

•    To upload files, the getInputStream method is called to get the data input stream, so that the uploaded data can be read.

 

2.Specific operation

The realization of the idea:

Tools: MySQL, eclipse

First, two tables and a t_user table are created in MySQL to store personal information such as user name, password, etc.

A t_touxiang table is used to store the uploaded pictures in the server, as well as the picture name and user ID.

T_touxiangThe user ID in the table corresponds to the ID in the t_user.

t_userTable SQL:

DROP TABLE IF EXISTS `t_user`;  
CREATE TABLE `t_user` (  
  `id` int(10) NOT NULL AUTO_INCREMENT,  
  `username` varchar(20) NOT NULL,  
  `password` varchar(255) NOT NULL,  
  PRIMARY KEY (`id`),  
  UNIQUE KEY `username` (`username`)  
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT

T_touxiangTable SQL:

DROP TABLE IF EXISTS `t_touxiang`;  
CREATE TABLE `t_touxiang` (  
  `id` int(10) NOT NULL AUTO_INCREMENT,  
  `image_path` varchar(255) DEFAULT NULL,  
  `user_id` int(11) DEFAULT NULL,  
  `old_name` varchar(255) DEFAULT NULL,  
  PRIMARY KEY (`id`),  
  KEY `img_user` (`user_id`),  
  CONSTRAINT `img_user` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;  

First, write a UploadServlet.java to handle the upload of the picture file, and store the picture path, the picture name and other information into the t_touxiang data table. The code is as follows:

package filet;

import java.awt.List;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

public class tr {
    @WebServlet("/UploadServlet.do")  
    public class UploadServlet extends HttpServlet {  
        private static final long serialVersionUID = 1L;  
      
        protected void service(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        // Determine whether the upload form is multipart/form-data type.
        HttpSession session = request.getSession();  
        User user = (User) session.getAttribute("user"); // The User object is placed in the session at logon// in
      
        if (ServletFileUpload.isMultipartContent(request)) {  
      
            try {  
            // 1. Create DiskFileItemFactory object, set buffer size and temporary file directory
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            // System.out.println(System.getProperty("java.io.tmpdir"));//Default temporary folder//Determine whether temporary directory exists (no creation is created).
                    File f1 = new File(tempPath);
                      if(!f1.isDirectory()){
                          System.out.println("Temporary file directory does not exist! Create temporary file directory ");
                           f1.mkdir();
                       }
          //The temporary directory for uploading files is different from the default directory.
             factory.setRepository(f1); 
      
            // 2. Create ServletFileUpload object and set the size limit for uploading files.
            ServletFileUpload sfu = new ServletFileUpload(factory);  
            sfu.setSizeMax(10 * 1024 * 1024);// The byte unit cannot exceed the 10M 1024byte = =// 1kb 1024kb=1M 1024M = 1G  
            sfu.setHeaderEncoding("utf-8");  
      
            // 3.  
            // Call the ServletFileUpload.parseRequest method to parse the request object and get a List object that holds all uploaded content.
            @SuppressWarnings("unchecked")  
            List<FileItem> fileItemList = sfu.parseRequest(request);  
            Iterator<FileItem> fileItems = fileItemList.iterator();  
      
            // 4. Traversing list, each iteration of a FileItem object, calling its isFormField method to determine whether it is uploaded file.
            while (fileItems.hasNext()) {  
                FileItem fileItem = fileItems.next();  
                // Common form element
                if (fileItem.isFormField()) {  
                String name = fileItem.getFieldName();// nameAttribute value
                String value = fileItem.getString("utf-8");// nameCorresponding value values
      
                System.out.println(name + " = " + value);  
                }  
                // <input type="file">The elements of the uploaded file
                else {  
                String fileName = fileItem.getName();// File name
                System.out.println("Original file name: "+ fileName";// Koala.jpg  
      
                String suffix = fileName.substring(fileName.lastIndexOf('.'));  
                System.out.println("Extension: "+ suffix";// .jpg  
      
                // New file name (only)
                String newFileName = new Date().getTime() + suffix;  
                System.out.println("New file name: "+ newFileName";// image\1478509873038.jpg  
      
                // 5. Call the FileItem's write () method to write the file
                File file = new File("D:/xiaobaiProjects/mySpace/wendao/WebContent/touxiang/" + newFileName);  
                System.out.println(file.getAbsolutePath());  
                fileItem.write(file);  
      
                // 6. Call the delete () method of FileItem to delete temporary files.
                fileItem.delete();  
      
                /* 
                 * When storing to the database, note 1. save the source file name Koala.jpg 2. to save the relative path.* image/1478509873038.jpg**/  
                if (user != null) {  
                    int myid = user.getId();  
                    String SQL = "INSERT INTO t_touxiang(image_path,user_id,old_name)VALUES(?,?,?)";  
                    int rows = JdbcHelper.insert(SQL, false, "touxiang/" + newFileName, myid, fileName);  
                    if (rows > 0) {  
                    session.setAttribute("image_name", fileName);  
                    session.setAttribute("image_path", "touxiang/" + newFileName);  
                    response.sendRedirect(request.getContextPath() + "/upImage.html");  
                    } else {  
      
                    }  
      
                } else {  
                    session.setAttribute("loginFail", "Please log in ");  
                    response.sendRedirect(request.getContextPath() + "/login.html");  
                }  
      
                }  
            }  
      
            } catch (FileUploadException e) {  
            e.printStackTrace();  
            } catch (Exception e) {  
            e.printStackTrace();  
            }  
      
        }  
        }  
    }  
}

While uploading pictures and writing to the database, the picture path is sent to the HTML interface through session.

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Replace the head image < /title>< /head>< body>< formaction= "UploadServlet.do" method= "Post "enctype=" multipart/form-data ">

                     Local directory:<inputtype="file" name="uploadFile">

           <img src="${image_path}" width="200" height="200">

                <inputtype="submit" value="Upload the head image "/>< /form>< /body>< /html>

So far, the uploaded database and local server have been implemented. How can we display personal information and upload the avatar on the HTML interface?

First, define a PersonServlet class to read the contents of the database and send it to the HTML interface.

The code is as follows:

@WebServlet("/persons.do")
public class PersonServlet extends HttpServlet {

    private static final long serialVersionUID = -800352785988546254L;

    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Determine whether the upload form is multipart/form-data type.
    Touxiang tx=null;
    
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user"); // The User object is placed in the session at logon
    if(user!=null){
        int myid=user.getId();
        String SQL="SELECT id,image_path,old_name FROM t_touxiang WHERE user_id=?";
        ResultSet rs=JdbcHelper.query(SQL,myid);
        String uSQL="SELECT username,password FROM t_user WHERE id=?";
        ResultSet urs=JdbcHelper.query(uSQL,myid);
        System.out.println( "My personal ID is: "+ myid);
        final List<Touxiang> touxiang=new ArrayList<>();
        try {
        if(rs.next())
        {
            tx=new Touxiang();
            tx.setId(rs.getInt(1));
            tx.setImage_path(rs.getString(2));
            tx.setOld_name(rs.getString(3));
            touxiang.add(tx);
        }
        if(urs.next()){
            user.setUsername(urs.getString(1));
            user.setPassword(urs.getString(2));
            user.setTouxiang(touxiang);
        }
        
        } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
       
        session.setAttribute("user", user);
        System.out.println( "My id: "+" myid);
        response.sendRedirect( request.getContextPath() + "/person.html");
    }
    }
}

Receive information on the HTML interface and display it. The code is as follows:

<span style="white-space:pre;">    </span><div>
    <form action="UploadServlet.do" method="post" enctype="multipart/form-data">
               <div><a href="$path/upImage.html">Change the head image < /a> < /div>
            
            #foreach( $ut in  $user.getTouxiang() )
             <img src=" $ut.getImage_path()"  width="200" height="200">
             #end
             <div>My head: < /div>< div> my name: $user.getUsername () < /div>< div≫ < a href= "$path/myAnswer.do" > my answer < /a> < /div>< div> < a href= "$path/myQuestion.do ">"; my question < /a> < /div>< span style= "white-space:pre;" > < /span≫ < /form>< /div>

At this point, a Java based upload server, the path stored in MySQL, and the function read out on the HTML interface is basically realized. Before you upload your head, you can choose some plug-ins to do it. This is just a simple implementation of the basic functions.

 3.download

The principle of downloading files through Servlet is to read the target program through servlet and return the resources to the client.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Download the file < by link; /h1>< a href= "/xiaobai/download/cors.zip" > compressed packet < /a>< a href= "/xiaobai/doWnload/1.png "> picture < /a>< h1> download files < /h1> through servlet program;< a href= "/xiaobai/ServletDownlOad? Filename=cors.zip "> compressed packet < /a>< a href= "/xiaobai/ServletDownload? Filename=1.png" > image &lT; /a>< /body>< /html>
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletDownload
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })
public class ServletDownload extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletDownload() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        //Obtaining the request file name
        String filename = request.getParameter("filename");
        System.out.println(filename);
        
        //Setting the file MIME type
        response.setContentType(getServletContext().getMimeType(filename));
        //Setting up Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename="+filename);
        //Read the target file and write the target file to the client through response.//Get the absolute path of the target file
        String fullFileName = getServletContext().getRealPath("/download/" + filename);
        //System.out.println(fullFileName);
        //read file
        InputStream in = new FileInputStream(fullFileName);
        OutputStream out = response.getOutputStream();
        
        //Write a document
        int b;
        while((b=in.read())!= -1)
        {
            out.write(b);
        }
        
        in.close();
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

 

supplement

For uploading pictures, this is just a simple realization of the most basic functions with Servlet, providing only ideas. If you use spring and other frameworks, he will do a good encapsulation of image uploading. It should be easier.

Backstage to upload pictures should be easier, but the headache is the picture uploaded the original button ugliness out of the sky, here recommended two practical upload controls, should be more beautiful.

 

1,H5Upload pictures can be uploaded more than one, click to drag and upload.

Basic introduction and download address: http://blog.csdn.net/weixin_36380516/article/details/70352689

2,jQueryImage clipping plug-in, probably like this

Not only uploads, but also functions such as tailoring. UI is also beautiful.

Address: http://www.jq22.com/jquery-info318

Leave a Reply

Your email address will not be published. Required fields are marked *