JavaEE网络编程篇

18.实现网站上选择本地图片并上传至服务器

2022-08-09  本文已影响0人  一直流浪

功能介绍:

本地选择照片上传至服务器。

需要引入的 jar 文件:commons-fileupload-1.3.2、commons-io-2.5.jar。

下载链接:

将下载好的jar包复制到项目/WebContent/WEB-INF/lib 文件夹下:

实现代码:

fileUpload2.jsp:图片上传的界面页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link type="text/css" rel="stylesheet" href="../css/fileUpload2.css" />
</head>
<body >
<form action="/JavaEE17ToolDemo/file-upload-servlet" method="post" enctype="multipart/form-data">
<img alt="" id="img1" src="" style="height:300px;width: 200px">
<a class="a-upload">
  <input type="file" name="file" id="fileField" onchange="document.getElementById('img1').src=document.getElementById('fileField').value">点击这里上传文件
</a>
<br/>
    <input type="submit" value="上传">
</form>
</body>
</html>

fileUpload2.css: css文件

@charset "UTF-8";

body{
    background-color: skyblue;
}

#img1{
    background-color: white;
}

.a-upload {
    padding: 4px 10px;
    height: 20px;
    line-height: 20px;
    position: relative;
    cursor: pointer;
    color: #888;
    background: #fafafa;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    display: inline-block;
    *display: inline;
    *zoom: 1
}

#img1{
    width:100px;
    height:100px;
}

.a-upload  input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer
}

.a-upload:hover {
    color: #444;
    background: #eee;
    border-color: #ccc;
    text-decoration: none
}

.file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}

FileUploadServlet.java:文件上传处理

package com.company.project.servlet.fileupload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/file-upload-servlet")
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 文件上传的存储路径
    private static final String SAVE_PATH = "imag";

    // 上传配置
    // 配置内存临界值
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    // 配置最大文件大小
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    // 配置请求大小
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    public FileUploadServlet() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检测是否为多媒体文件
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter out = response.getWriter();
            out.println("表单必须包含 enctype=multipart/form-data");
            out.flush();
            out.close();
            return;
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置上传文件最大值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值(包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 创建保存路径
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + SAVE_PATH;

        // 如果路径不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                //迭代表单数据
                for (FileItem fileItem : formItems) {
                    //处理不在表单的字段
                    if(!fileItem.isFormField()) {
                        String fileName = new File(fileItem.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        System.out.println(filePath);
                        // 保存文件到硬盘
                        fileItem.write(storeFile);
                        request.setAttribute("message",
                            "文件上传成功!");
                    }
                }
            }

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            request.setAttribute("message",
                    "错误信息: " + e.getMessage());
        }

        //文件上传完成跳转
        request.getServletContext().getRequestDispatcher("/page/UploadMes.jsp").forward(request, response);
    }
}

UploadMes.jsp:文件传输完成跳转页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传结果</title>
</head>
<body>
<center>
    <h2>${message }</h2>
</center>

</body>
</html>

效果图:


上一篇下一篇

猜你喜欢

热点阅读