JavaWeb achieve local file upload function

 

Web upload files mainly divided into two steps

  1. Set an upload file option in the Web page, usually accomplished by <form> <input> tags two

  2. Servlet class to read uploaded files, and saved to the server

 

Several places before recording the first line and the steps to achieve it again should be noted, as well as introduce two jar package and class

Needs attention

  1. <Input> type attribute is set for the entry of 'file', and the name attribute must be set, otherwise the browser will not send data upload file

  2. <Form> Form method attribute must be set to 'post' mode, enctype attribute is set to 'multipart / form-data'

Introduction to use a jar and classes
  1. To address user needs to upload multiple files at one time, Apache provides a component FileUploat, this document implements upload multiple files at the same time and can limit upload file size, use this component needs to Apache official website to download two jar package: commons -fileupload-1.4.jar, commons-io-2.6.jar

  2. To use FileUpload assembly FileItem interfaces, DiskFileItemFactory ServletFileUpload classes and class (class of these methods do not write, direct use in the project)

With a picture on it clearly shows the effect of these classes

 

 

Here are the steps to achieve

 

The first step: introducing two jar package to use the above-mentioned

Step 2: Create the upload page

<%-- Created by IntelliJ IDEA. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>

</head>
<body>

<form enctype="multipart/form-data" method="post" action="cn.itcast.fileupload.UploadServlet">

    <%--上传者--%>
    <input type="text" name="name"
    <the INPUT of the type =
    <% - upload files -%>>"file" name="myfile">
    <input type="submit" value="上传">

</form>
</body>
</html>

 

 

Step 3: Create a Servlet class, upload files to be processed

package cn.itcast.fileupload;

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 javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

public class UploadServlet extends HttpServlet {

    private static final long= serialVersionUID 1L ; 

    @Override 
    protected  void the doGet (the HttpServletRequest REQ, the HttpServletResponse RESP) throws ServletException, IOException { 

        the try {
 //             set ContentType field 
            resp.setContentType ( " text / HTML; charset = UTF8 " );
 //           Create DiskFileItemFactory factory object, each request may be a message entity file into individual packaged objects FielItem 
            DiskFileItemFactory Factory = new new DiskFileItemFactory (); 

//           set the cache directory file, if the file does not exist, create a new 
            file F = new new file ( " / the Users / liuliu / Desktop / My ");
             IF (! ) {F.exists () 
                f.mkdir (); 
            } 

//             cache path settings file 
            factory.setRepository (F);
 //             Create a ServletFileUpload objects 
            ServletFileUpload fileUpload = new new ServletFileUpload (Factory);
 //             set character encoding 
            fileUpload.setHeaderEncoding ( " UTF-. 8 " ); 

//             parse request, upload files to obtain the object FileItem 
            List <FileItem> fileItems = fileUpload.parseRequest (REQ);
 //             Get the character stream 
            PrintWriter writer =resp.getWriter (); 

//             traverse the object fileItems List object set 
            for (FileItem FileItem: fileItems) {
 //                 determine the current target FileItem encapsulated data is "plain text form field" 
                IF (fileItem.isFormField ()) {
 / /                     get uploaded form field name attribute 
                    string name = fileItem.getFieldName ();
                     IF (name.equals ( " name " )) {
 //                         if the stored data in the object FileItem stream is not empty, then a string is returned and by print output 
                        IF (! fileItem.getString (). the equals ( "" )) { 
                            String value = fileItem.getString ( ". 8-UTF " ); 
                            writer.print ( " By: " + value + " a " ); 
                        } 
                    } 
                } the else { // determination data of the current object encapsulates FileItem is" document form fields "
 //                     get the file name of the uploaded file 
                    String filename = fileItem.getName ();
                     IF (! FileItem = null ! && fileItem.equals ( "" )) { 
                        writer.print ( " file name uploading " + filename + "a " );
 //                         intercepting a file name 
                        filename = filename.substring (filename.lastIndexOf ( " \\ " ) + . 1 );
 //                         given a unique file name ID 
                        filename = UUID.randomUUID (). toString () + " _ " + filename; 

//                         create a file with the same name in the server 
                        String webPath = " / myima / " ;
 //                         the server and folder path name of the file server into a complete path
                        GetServletContext filePath = String () getRealPath (webPath +. Filename); 

//                         create the file 
                        File File = new new File (filePath); 
                        file.getParentFile () mkdir ();. 
                        File.createNewFile (); 

//                         get file upload stream 
                        InputStream in = fileItem.getInputStream ();
 //                         open the file upload server 
                        FileOutputStream FileOutputStream = new new FileOutputStream (file); 

//                         Duikao stream 
                        byte buffer[] = new byte[1024];
                        int len;
                        while ((len = in.read(buffer)) > 0) {
                            fileOutputStream.write(buffer, 0, len);
                            in.close();
                            fileOutputStream.close();
                            fileItem.delete();
                            writer.print("上传文件成功");

                        }
                    }
                }
            }


        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}

 

 

Upload a few files to test the next, you can see myima file is successfully created, the file has successfully uploaded to here

 

Guess you like

Origin www.cnblogs.com/lyd447113735/p/11985568.html