javaWeb-5-File upload and file download

table of Contents

1. File upload

1.1 Steps to upload files

1.2 Code demonstration of file upload-project structure

1.2.1 Write a front-end page for upload operation: upload.html

1.2.2 Write a back-end dynamic resource processor: UploadServlet

1.2.3 Configure the dynamic resource access path in the web.xml file

1.2.4 File upload test

1.2.2-1 HTTP protocol content format sent by the client during file upload

1.2.2-2 Description of the jar package used when uploading files: commons-fileupload common API

2. File download

2.1 File download overall project structure

2.2 Write a dynamic servlet processor for download

2.3 Configure the Servlet access path in the web.xml file

2.4 Pre-place static resources in the Tomcat server

2.5 Visit the download link in the front-end browser to see the download effect

2.6 Solving the problem of Chinese encoding by different browsers

1. File upload

1.1 Steps to upload files

1.2 Code demonstration of file upload-project structure

1.2.1 Write a front-end page for upload operation: upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/07_servlet/uploadServlet" method="POST" enctype="multipart/form-data">
    用户名:<input type="text" name="username"><br/>
    头像:<input type="file" name="photo"><br/>
    <input type="submit" name="上传">
</form>
</body>
</html>

1.2.2 Write a back-end dynamic resource processor: UploadServlet

package com.wind.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
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.File;
import java.io.IOException;
import java.util.List;

/**
 * 测试文件上传
 */
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = -9188824273706312794L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost文件上传过来了...");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        //1.先判断上传的数据是否是多段数据(只有是多段的数据,才是文件上传的)
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建FileItemFactory接口的工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //3.创建用于解析上传文件数据的工具类ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //4.解析上传文件数据,得到一个表单项数组
            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);
                //5.循环判断每一个表单项是普通数据还是上传的文件
                for (FileItem fileItem : fileItems) {
                    if (fileItem == null) {
                        continue;
                    }
                    if (fileItem.isFormField()) {
                        //如果是普通的表单项
                        System.out.println("表单项的name属性值=" + fileItem.getFieldName());
                        System.out.println("表单项的value属性值=" + fileItem.getString("UTF-8"));

                    } else {
                        //如果是上传的文件类型
                        System.out.println("表单项的name属性值=" + fileItem.getFieldName());
                        System.out.println("表单项的上传文件名=" + fileItem.getName());
                        fileItem.write(new File("/Users/cmm/upload/" + fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet...");
    }
}

1.2.3 Configure the dynamic resource access path in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>DownloadServlet</servlet-name>
        <servlet-class>com.wind.servlet.DownloadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/uploadServlet</url-pattern>
    </servlet-mapping>

</web-app>

1.2.4 File upload test

(1) Client fills in information

(2) The uploaded file has appeared on the local disk after the upload is complete

(3) The output of the Tomcat server

1.2.2-1 HTTP protocol content format sent by the client during file upload

1.2.2-2 Description of the jar package used when uploading files: commons-fileupload common API

(1) For the HTTP protocol content format sent by the client during file upload, there are already mature third-party jar packages for us to use.

(2) The jar download address : https://mvnrepository.com/ 

2. File download

2.1 File download overall project structure

2.2 Write a dynamic servlet processor for download

package com.wind.servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 用于测试下载
 */
public class DownloadServlet extends HttpServlet {

    private static final long serialVersionUID = 8594037586209694672L;

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet...");
        //1.获取要下载的文件名(这里就直接hardcode了)
        String downloadFileName = "2.jpg";
        /**
         * 斜杠 / :在服务器端被解析为:http://ip:port/工程项目/,映射到IDEA代码中的WEB目录
         */
        String downloadFilePath = "/WEB-INF/file/" + downloadFileName;

        //2.读取要下载的文件内容(通过ServletContext对象可以读取)
        ServletContext servletContext = getServletContext();

        //3.读取要下载的文件类型
        String mimeType = servletContext.getMimeType(downloadFilePath);

        //4.在回传前,需要通过响应头告知客户端服务器返回的数据类型
        response.setContentType(mimeType);

        //5.还要通过响应头告知客户端,你收到的数据是用于下载还是用于页面展示
        //Content-Disposition:响应头,表示客户端收到的数据该怎么处理
        //attachment:表示是附件,用于下载
        //filename:表示指定下载的文件名
        //如果filename含有中文则会乱码,解决:URL编码是把中文转换为%xx%xx的格式
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("中国.jpg", "UTF-8"));
        //response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName);

        //6.把下载的文件内容回传给客户端
        InputStream resourceAsStream = servletContext.getResourceAsStream(downloadFilePath);
        //获取响应的输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //读取输入流中的全部数据,复制给输出流,并且返给客户端
        IOUtils.copy(resourceAsStream, outputStream);
    }
}

2.3 Configure the Servlet access path in the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>DownloadServlet</servlet-name>
        <servlet-class>com.wind.servlet.DownloadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>DownloadServlet</servlet-name>
        <url-pattern>/downloadServlet</url-pattern>
    </servlet-mapping>

</web-app>

2.4 Pre-place static resources in the Tomcat server

2.5 Visit the download link in the front-end browser to see the download effect

2.6 Solving the problem of Chinese encoding by different browsers

 

 

Guess you like

Origin blog.csdn.net/cmm0401/article/details/111461978