Servlet 上传图片
阅读原文时间:2023年07月09日阅读:3

目录

Servlet 上传图片

预备

需求包

commons-fileupload -用于上传

jstl -用于jsp页面遍历

servlet-api -使用servlet

pom

    <dependencies>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传Demo</title>
</head>
<body>
    <form action="uploadServlet" method="post"
        enctype="multipart/form-data">

        上传文件:<input type="file" name="file"><br/>
        上传文件:<input type="file" name="file2"><br/>
        <input type="submit" />
    </form>
    <c:forEach items="${pics }" var="p">
    <img src="heads/${p }" />
    </c:forEach>
</body>
</html>

后端处理代码

package com;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

@WebServlet("/uploadServlet")
public class uploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public uploadServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.sendRedirect("index.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 是否是多功能表单
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            return;
        }

        // 目标服务端目录
        String path = request.getSession().getServletContext().getRealPath("/heads");
        // String path="D:/heads";
        File file = new File(path);

        // 如果目录不存在就创建目录
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }

        // 接受文件列表
        List piclist = new ArrayList(); // 放上传的图片名

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setHeaderEncoding("UTF-8"); // 处理中文问题
        upload.setSizeMax(1024 * 1024 * 5); // 限制文件大小5M

        try {
            // 得到所有表单元素
            List<FileItem> fileItems = upload.parseRequest(request); // 解码请求

            for (FileItem item : fileItems) {
                System.out.println(item);
                // 有可能是 文件,也可能是普通文字
                if (item.isFormField()) { // 这个选项是 文字
                    System.out.println("表单值为:" + item.getString());
                } else {
                    // 是文件
                    String fileName = item.getName();
                    System.out.println("文件名是:" + fileName); // 文件名
                    item.write(new File(path, fileName));

                    if (fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".bmp") || fileName.endsWith(".ico") || fileName.endsWith(".gif")) {
                        piclist.add(fileName); // 把图片放入集合
                    }
                }
            }

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

        // 去显示上传的文件
        request.setAttribute("pics", piclist);
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章