文件的上传、下载(Servlet)

本文介绍了如何使用Servlet实现文件的上传和下载功能,包括引入依赖、编写UploadServlet和DownloadServlet,创建提示页面message.jsp,配置web.xml以及展示上传结果和路径。
摘要由CSDN通过智能技术生成

1.引入依赖

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

2.编写上传类UploadServlet.java

import org.apache.commons.fileupload.FileItem;
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;

public class UploadServlet extends HttpServlet {
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
    private static final String UPLOAD_DIRECTORY = "upload";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h2>");
        out.println("hi");
        out.println("</h2>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (!ServletFileUpload.isMultipartContent(req)) {
            PrintWriter out = resp.getWriter();
            out.println("表单type错误,必须包含 enctype=multipart/form-data");
            out.flush();
            out.close();
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        upload.setHeaderEncoding("UTF-8");

        String uploadPath =  req.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists())
            uploadDir.mkdir();
        try {
            List<FileItem> fileItems = upload.parseRequest(req);

            if (fileItems == null || fileItems.size() == 0) {
                req.setAttribute("message", "没有有效文件");
            }
            for (FileItem item : fileItems) {
                if (!item.isFormField()) { // 判断表单是否是file类型(false为file)
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    System.out.println(item.getString("gbk"));

                    FileOutputStream fout = new FileOutputStream(storeFile);
                    OutputStreamWriter oStreamWriter = new OutputStreamWriter(fout,"gbk");
                    oStreamWriter.append(item.getString("gbk"));
                    oStreamWriter.flush();
                    oStreamWriter.close();
                    req.setAttribute("message", "文件上传成功");
                }
            }
        } catch (Exception e) {
            req.setAttribute("message",
                    "错误信息: " + e.getMessage());
        }
        req.getServletContext().getRequestDispatcher("/message.jsp").forward(req, resp);
    }
}

3.编写下载类DownloadServlet.java

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.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 暂时写死了路径
        File file = new File("E:\\workspace\\servlet-study\\target\\servlet-study\\upload\\girl.jpg");
        if (!file.exists()) {
            req.setAttribute("message", "下载文件不存在");
            req.getServletContext().getRequestDispatcher("/message.jsp").forward(req, resp);
        }
        FileInputStream fis = new FileInputStream(file);
        String filename = URLEncoder.encode(file.getName(),"utf-8"); //解决中文文件名下载后乱码的问题
        byte[] b = new byte[fis.available()];
        fis.read(b);

        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
        ServletOutputStream out = resp.getOutputStream();
        out.write(b);
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
3.编写上传页面(index.jsp)
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>文件上传</title>
    </head>
    <body>
        <h2>文件上传!</h2>
        <form method="post" action="/uploadServlet" enctype="multipart/form-data">
            选择一个文件
            <input type="file" name="uploadFile">
            <br/>
            <br/>
            <input type="submit" value="上传">
        </form>
    </body>
</html>

4.结果提示页面(message.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"  pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>文件上传结果</title>
    </head>
    <body>
        <h2>${message}</h2>
    </body>
</html>

5.web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>testServlet</servlet-name>
        <servlet-class>com.fee.controller.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>testServlet</servlet-name>
        <url-pattern>/testServlet</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>uploadServlet</servlet-name>
        <servlet-class>com.fee.controller.UploadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>uploadServlet</servlet-name>
        <url-pattern>/uploadServlet</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>downloadServlet</servlet-name>
        <servlet-class>com.fee.controller.DownloadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>downloadServlet</servlet-name>
        <url-pattern>/downloadServlet</url-pattern>
    </servlet-mapping>
</web-app>

6.上传结果及路径




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值