JavaWeb the file upload and download

In today's Internet age, more and more people like to store their data on the Internet, so they gave birth to many types of software, such as a class of 360 network disk, network disk Baidu cloud disk of. So, file upload and download functionality is now very mainstream function, is widely used.
So, now, we have to learn about, in the web, how to achieve file upload and download!
Web development implementation file upload feature, complete the following two-step operation:
add upload entries in a web page
to read the data uploaded file in a servlet, and saved to the server's hard drive.
How to add entries uploaded in the web page?
Tag is used to add file upload in a web page entry, it should be noted when setting file upload entries:
1, it is necessary to set the name attribute input entry, otherwise the browser will not send data to upload files.
2, the form must be set to the value of the genus enctype multipart / form-data. When this value is, the browser uploading a file, the data file will be included in the body of the http request message, and using the MIME protocol files uploaded description, to facilitate receiver to parse and process the uploaded data.
3, form submission if the post

This is the realization of the page, followed by the achievement of specific functions.

How to read in the Servlet file upload data, and saves it to the hard drive?
Request object provides a getInputStream method, you can read the data submitted by the client to come through this method. However, since the user may upload multiple files, reading data directly uploaded servlet program end, respectively, and the corresponding analytical data file is a very troublesome work.

Know the principle, we now write a case study.
New web project.
Creating upload.jsp file.

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
    <form action="/day20/upload">
        用户名:<input type="text" name="username"><br>
        上传文件:<input type="file" name="upload"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

Then we create a UploadServlet

package cn.itcast.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UploadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //request提供getInputStream,用来获得请求体
        InputStream in = request.getInputStream();
        int temp;
        while((temp = in.read()) != -1){
            System.out.write(temp);
        }
        System.out.flush();
        in.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

So that the code we write is complete, then we prepare a info.txt file for file uploads.

Defines methods that all servlets must implement. 

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. 

To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet. 

This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence: 

The servlet is constructed, then initialized with the init method. 
Any calls from clients to the service method are handled. 
The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized. 
In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright. 

Preparatory work has been done, and now we have to try to run it.
Here Insert Picture Description
Now we get through getInputStream method of the request object information of the entire body of the request, but the request was not just the body text in info.txt file, there are some other parameter information, we now how to get the text content it? The key to this place is that the dividing line, but some students may question if the information I have the text in such a period dividing line it? It is necessary to look at the information we request header.
Here Insert Picture Description
I.e. the parameters of the request header is the dividing line.
Although the same, and text content produced by the dividing line situation may also occur, but the probability is very small, almost negligible.
Now, we can be divided by the dividing line of the request body.
Respective portions of the segmented is then determined, which is a text content. Judgment basis: to determine which part contains fliename and content-type, to prove its text content.
The principle is this, I will not achieve the specific interest of a write can write your own.

Along the way, you'll find yourself actually achieve file upload and download is very troublesome, but fortunately we have a ready-made tool can be used.
For the convenience of the user data file upload process, Apache open source provides an open source component (Commons-fileupload) used to process a file upload form, the superior component performance, and its use is extremely simple API that allows developers to easily implement web files Upload function, thus achieving file upload functionality in web development, usually Commons-fileupload component implementation.
Need to know is, after Servlet3.0, Servlet program itself supports file uploads.

But we still need to learn about the use of the jar. Here is the Download a jar.
Link: https: //pan.baidu.com/s/1F-fS7JgfilSF9bLA8iVQuQ
extraction code: 3kfh
copy the contents of this open Baidu network disk phone App, the operation more convenient oh

After the download is complete, add the jar package to our project.
Then I will brief you use.
1, a parser configured by the factory DiskFileItemFactory ServletFileUpload
2, with various portions of the body parser request dividing line is divided to obtain a plurality of portions, each portion is a the FileItem
. 3, the FileItem provides many API, you can be by isFormField determine whether the part is not a file upload item
4, if a file upload item, you can get the content upload files through getInputStream, get the name of the uploaded file by getName
5, if not a file upload items can be obtained by getFieldName upload form item name property, property value obtained upload form item by getString

Next, we use third-party API to upload files to achieve it.

package cn.itcast.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
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;

public class UploadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //request提供getInputStream,用来获得请求体
        // InputStream in = request.getInputStream();
        // int temp;
        // while((temp = in.read()) != -1){
        // System.out.write(temp);
        // }
        // System.out.flush();
        // in.close();
        
        //步骤一   构造工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
        //步骤二   获得解析器
        ServletFileUpload upload = new ServletFileUpload(factory);  
        
        //步骤三   对请求体内容进行解析
        try {
            List<FileItem> fList = upload.parseRequest(request);
            
            //步骤四   遍历集合
            for(FileItem fileItem : fList){
                //步骤五   判断每个fileItem是不是文件上传项
                if(fileItem.isFormField()){
                    //不是上传文件
                    String name = fileItem.getFieldName();
                    String value = fileItem.getString();
                    System.out.println("普通form项:" + name + "---" + value);
                }else{
                    //是上传文件
                    String fileName = fileItem.getName();
                    //解决老版本浏览器文件路径问题
                    if(fileName.contains("\\")){
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    }
                    InputStream in = fileItem.getInputStream();//得到的是文件内容
                    System.out.println("文件上传项:" + fileName);
                    //将内容写入文件
                    File file = new File("C:\\Users\\Administrator\\Desktop\\info_test.txt");
                    if(!file.exists()){
                        //文件不存在,创建文件
                        file.createNewFile();
                    }
                    FileOutputStream out = new FileOutputStream(file);
                    int len;
                    while((len = in.read()) != -1){
                        out.write(len);
                    }
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

Then run the project, it will generate a new file on the desktop, open the file, find the text has been successfully written to the file.

In this way, a very simple case file upload is complete. Next, we conducted a detailed study of core classes FileUpload tool.

The core API - DiskFileItemFactory

DiskFileItemFactory object is created FileItem factory, factory class common methods:
public DiskFileItemFactory (int the sizeThreshold, java.io.File Repository)
Constructor

public void setSizeThreshold (int sizeThreshold)
the size of the memory buffer is provided, the default value is 10K. When uploading files larger than the buffer size, fileupload component will use a temporary file cache to upload files.

public void setRepository (java.io.File repository)
specify the temporary file directory, the default value System.getProperty ( "java.io.tmpdir").

Note: Priority upload files saved in the contents of the buffer, when the memory buffer is not enough, it will generate a temporary file on the hard disk, temporary files, temporary files saved in the specified directory with the same contents of the temporary file with the source file.
How then to solve the Chinese garbage problem, some students might ask, post request processing garbage problem, use requeset.setCharacterEncoding ( "utf-8") is not on line yet, it really would not be here, I do not believe, then you can test yourself a try. In fact, the API provided in the parser to solve the Chinese garbled. You only need to use ServletFieUpload object to call setHeaderEncoding ( "utf-8") method can be solved.
Another problem is that with the increasing number of requests, the temporary file server will be more and more, which increased the burden on the server, so when upload is complete, we should delete the temporary files. In the last call FileItem object program delete () method to delete.

The core API - ServletFileUpload

ServletFileUpload responsible for processing the uploaded file data, and each entry is encapsulated into a form FileItem object. Common methods:
Boolean isMultipartContent (the HttpServletRequest request)
determines the upload form whether multipart / form-data type
List parseRequest (HttpServletRequest request)
analyzing request object and each form entries packed into a fileItem object and returns a save collection list of all FileItem.
setFileSizeMax (long fileSizeMax)
providing a single upload maximum
setSizeMax (long sizeMax)
provided the total amount of uploaded files maximum
setHeaderEncoding (java.lang.String encoding)
provided encoding format
setProgressListener (ProgressListener pListener)
monitor in real time the state of the file upload

Note: If the file is uploaded, we can get the file name by getFieldName () method, if not a file upload, we can get the name attribute of the form item by getName () method, getValue () method to obtain the value of form item, which, getValue () method if the data obtained are Chinese, will be garbled, this time, the basic processing garbled API do not work, but do not worry, we can use the API it provides. It overrides a getString (java.lang.String encoding) method, simply utf-8 as a parameter can be.

Guess you like

Origin www.cnblogs.com/blizzawang/p/11411699.html