美文网首页JavaEE网络编程篇
18.实现网站上选择本地图片并上传至服务器

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

作者: 一直流浪 | 来源:发表于2022-08-09 16:38 被阅读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>

效果图:


相关文章

  • Flask部署OCR

    情形一:图片在服务器上,传输图片在服务器上的地址 Client: Server: 情形二:图片保存在本地,上传至服...

  • 选择本地照片或拍照

    需求:app需要一个功能,选择本地图片或拍照上传服务器作为头像,此示例只能选择一张图片。实现:1.选择本地图片:方...

  • Web 基础26 文件上传概述及其入门案例

    1.1 文件上传概述 文件上传用户将本地文件通过网络上传至服务器的过程 应用场景相亲网站的照片上传招聘网站的简历上...

  • 微信小程序实现多张图片的一次性上传,删除,预览,点击按钮上传至云

    一:实现功能 实现从本地文件中一次选择上传多张图片 长按可删除图片 单击可预览图片 点击按钮上传至小程序云平台的云...

  • Android实现头像上传

    Android实现本地上传图片并设置为圆形头像 Android实现类似换QQ头像功能(图片裁剪) android上...

  • 关于屏幕截图的一些事儿

    实现截图并上传到服务器 截图 序列化到本地 图片上传

  • iOS 图片上传至服务器

    在做项目的时候, 我们会遇到用户头像上传至服务器的功能, 还有就是用户发表动态选择本地图片上传服务器的功能.但总归...

  • Web

    web图片 图片处理服务器用来处理网站上传的图片满足大小、旋转等要求 图床:将本地图片上传到网络图片服务器,生成网...

  • Vue 图片压缩并上传至服务器

    本文主要讲解基于 Vue + Vant ,实现移动端图片选择,并用 Canvas 压缩图片,最后上传至服务器。还会...

  • 图片上传总结(IE9拜拜)

    一、需求 (1)点击图片 Icon,出现文件上传框,选择图片;(2)验证图片类型及大小,本地预览的同时上传到服务器...

网友评论

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

    本文链接:https://www.haomeiwen.com/subject/kneqwrtx.html