第十五章 文件上传

news2024/9/24 23:32:45

目录

一、文件上传注意点

二、JavaWeb上传文件的核心

 三、常规的JavaWeb上传实现

四、运行效果


一、文件上传注意点

1. 为保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如放于WEB-INF目录下。

2. 为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名。

3. 要限制上传文件的最大值

4. 可以限制上传文件的类型,在收到上传文件名时,判断后缀名是否合法。

二、JavaWeb上传文件的核心

JavaWeb文件上传的核心是使用Servlet API中的javax.servlet.http.Part接口,它代表了一个HTML表单中的文件字段或其他类型的数据字段,以下是简单的代码示例:

@WebServlet("/upload")
@MultipartConfig(maxFileSize = 16177215) // 设置最大文件大小
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part filePart = request.getPart("file"); // 获取上传的文件
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // 获取文件名
 
        // 保存文件逻辑(这里需要自己实现)
        // 例如,保存到服务器的某个目录
        filePart.write(Paths.get("uploadDir", fileName).toString());
 
        // 响应
        response.getWriter().println("File " + fileName + " uploaded successfully");
    }
}
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>UploadFile</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>UploadFile Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Apache Commons FileUpload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

    <!-- Apache Commons IO -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.13.0</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>UploadFile</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.4.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.3.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.13.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>3.3.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.4.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 三、常规的JavaWeb上传实现

我们通常会采用开源的Apache Commons FileUpload来实现文件上传,其中有几个比较重要的类。ServletFileUpload类负责处理上传的文件数据,使用其parseRequest(HttpServletRequest)方法将表单中每个输入项(比如表单中每一个HTML标签提交的数据)封装成一个FileItem对象,然后以List列表的形式返回,在使用ServletFileUpload对象解析请求时需要DiskFileItemFactory对象。所以,我们需要在进行解析工作前构造好DiskFileItemFactory对象,通过ServletFileUpload对象的构造方法或setFileItemFactory方法设置ServletFileUpload对象的fileItemFactory属性。大致的原理图如下:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>UploadFile</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>UploadFile Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Apache Commons FileUpload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

    <!-- Apache Commons IO -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.13.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>UploadFile</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.4.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.3.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.13.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>3.3.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.4.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
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.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 判断上传的文件是普通表单还是带文件的表单
        if (!ServletFileUpload.isMultipartContent(request)) {
            return; // 普通表单直接返回
        }

        // 创建上传文件的路径,建议在WEB-INF路径下,比较安全,用户无法直接访问上传的文件
        String filePath = getServletContext().getRealPath("/WEB-INF/uploads");

        // 创建固定的文件上传目录
        File uploadFile = new File(filePath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        // 缓存 临时文件
        // 假如文件超过预期大小,就把它放到一个临时文件中,设定指定时间后自动删除,或者提醒用户转存为永久
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
        File tmpFile = new File(tmpPath);
        if (!tmpFile.exists()) {
            tmpFile.mkdir();
        }
        // 处理文件的上传,一般都需要通过流来获取,我们可以使用request.getInputStream(),原生的文件上传流来获取。
        // 项目中为了代码健壮性和便捷性,使用开源封装好的工具来实现。common-fileupload(它依赖与commons-io组件)

        // 1. 创建DiskFileItemFactory,处理文件上传路径或者大小限制
        DiskFileItemFactory factory = new DiskFileItemFactory(); //
        factory.setSizeThreshold(1024 * 1024); // 设置缓冲区大小为1M
        factory.setRepository(tmpFile); // 临时保存文件的目录

        // 2. 获取ServletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 监听上传文件进度:
        upload.setProgressListener(new ProgressListener() {
            // l:已经读取到的文件大小
            // l1:文件大小
            @Override
            public void update(long l, long l1, int i) {
                System.out.println("总大小:" + l1 + "已上传:" + l);
            }
        });
        // 处理乱码问题
        upload.setHeaderEncoding("UTF-8");
        // 设置单个文件最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        // 设置总共能够上传文件的大小 10MB
        upload.setSizeMax(1024 * 1024 * 10);

        // 3. 处理上传的文件
        // 把前端请求解析,封装成一个FileItem对象,需要从ServletFileUpload对象中获取
        List<FileItem> fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        // fileItem 每一个表单对象
        for (FileItem fileItem: fileItems) {
            // 判断上传的文件是普通表单还是带文件的表单
            if (fileItem.isFormField()) {
                // getFiledName指的是前端表单控件的name
                String name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8");// 处理乱码
                System.out.println(name + ":" + value);
            } else {
                String uploadFileName = fileItem.getName();
                if (uploadFileName.trim().equals("") || uploadFileName == null) {
                    continue;
                }
                // 获取文件名
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                // 获取文件后缀
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                // 如果文件后缀名不是我们需要的,就不上传,该逻辑此处不做处理
                // 通过UUID生成一个唯一的路径
                String uuid = UUID.randomUUID().toString();
                // 文件真实存在的唯一路径
                String realPath = filePath + "/" + uuid;
                File realPathFile = new File(realPath);
                // 给每个文件创建一个文件夹
                if (!realPathFile.exists()) {
                    realPathFile.mkdir();
                }

                // 完整文件名 文件夹+文件名 /xx/xx/xx.jpg
                String completeFileName = realPath + "/" + fileName;
                // 获得文件上传流
                InputStream inputStream = fileItem.getInputStream();
                // 创建文件输出流
                FileOutputStream fos = new FileOutputStream(completeFileName);
                // 创建一个缓冲区
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;
                // 判断文件是否读取完毕
                while ((len = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                inputStream.close();

                // 输出文件流到上传文件路径下也可以这样写
                // fileItem.write(completeFileName);

                fileItem.delete(); //上传成功,删除临时文件
                request.setAttribute("msg", "文件上传成功");
                request.getRequestDispatcher("info.jsp").forward(request, response);
            }
        }
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app
    version="4.0"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:javaee="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xml="http://www.w3.org/XML/1998/namespace"
    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">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>uploadServlet</servlet-name>
    <servlet-class>servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>uploadServlet</servlet-name>
    <url-pattern>/upload.do</url-pattern>
  </servlet-mapping>
</web-app>
<!DOCTYPE html>
<%@page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<body>
<form action="${pageContext.servletContext.contextPath}/upload.do" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>
<!DOCTYPE html>
<%@page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<body>
${msg}
</body>
</html>

四、运行效果

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2161781.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[万字长文]stable diffusion代码阅读笔记

stable diffusion代码阅读笔记 获得更好的阅读体验可以转到我的博客y0k1n0的小破站 本文参考的配置文件信息: AutoencoderKL:stable-diffusion\configs\autoencoder\autoencoder_kl_32x32x4.yaml latent-diffusion:stable-diffusion\configs\latent-diffusion\lsun_churches-ld…

Unity图形用户界面!*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。(万字解析)

Unity 3D GUI 简介 游戏开发过程中&#xff0c;开发人员往往会通过制作大量的图形用户界面&#xff08; Graphical User Interface&#xff0c;GUI &#xff09;来增强游戏与玩家的交互性。 Unity 3D 中的图形系统分为 OnGUI、NGUI、UGUI等&#xff0c;这些类型的图形系统内容…

springboot项目引入了第三方jar包

应该把jar包放在resource目录下&#xff0c;新建一个lib目录放进去&#xff0c;不然打包的时候会报错找不到jar包&#xff0c;放入jar包&#xff0c;右键添加到库&#xff0c;才可以使用。 _g().startMarquee();

解决方案 | 镭速助力动漫游戏行业突破跨网文件交换瓶颈

在数字化浪潮推动下&#xff0c;动漫游戏行业蓬勃发展。随着高清技术的普及和云游戏的兴起&#xff0c;动漫游戏行业对动画的画质要求越来越高&#xff0c;数据量呈现爆炸式增长。然而&#xff0c;行业内的跨网文件交换难题也日益凸显&#xff0c;成为制约行业发展的瓶颈。 行业…

RTE大会报名丨 重塑语音交互:音频技术和 Voice AI,RTE2024 技术专场第一弹!

Voice AI 实现 human-like 的最后一步是什么&#xff1f; AI 视频爆炸增长&#xff0c;新一代编解码技术将面临何种挑战&#xff1f; 当大模型进化到实时多模态&#xff0c;又将诞生什么样的新场景和玩法&#xff1f; 所有 AI Infra 都在探寻规格和性能的最佳平衡&#xff0…

考研数据结构——C语言实现插入排序

插入排序是一种简单直观的比较排序算法&#xff0c;它的工作原理是通过构建有序序列&#xff0c;对于未排序数据&#xff0c;在已排序序列中从后向前扫描&#xff0c;找到相应位置并插入。插入排序在实现上&#xff0c;通常采用in-place&#xff08;原地排序&#xff09;&#…

BUUCTF [SCTF2019]电单车

使用audacity打开&#xff0c;发现是一段PT2242 信号 PT2242信号 有长有短&#xff0c;短的为0&#xff0c;长的为1化出来 这应该是截获电动车钥匙发射出的锁车信号 0 01110100101010100110 0010 0前四位为同步码0 。。。中间这20位为01110100101010100110为地址码0010为功…

neo4j小白入门

1.建立几个学校的节点 1.1创建一个节点的Cypher命令 create (Variable:Lable {Key1:Value,Key2,Value2}) return Variable 1.2创建一个学校的节点 create (n:School{name:清华大学,code: 10003,establishmentDate:date ("1911-04-29")})return n 1.3一次创建几个…

Ribbon布局和尺寸调整

Ribbon布局和尺寸调整 在本文中 Ribbon大小调整概述 默认大小调整行为 指定自定义调整大小行为 控件级调整 Ribbon使用自适应布局和调整大小来呈现各种窗口大小的最佳控件布局。Ribbon提供默认的大小调整行为&#xff0c;适用于许多常见场景。WPF的Microsoft Ribbon还提供了一…

【可图(Kolors)部署与使用】大规模文本到图像生成模型部署与使用教程

✨ Blog’s 主页: 白乐天_ξ( ✿&#xff1e;◡❛) &#x1f308; 个人Motto&#xff1a;他强任他强&#xff0c;清风拂山冈&#xff01; &#x1f4ab; 欢迎来到我的学习笔记&#xff01; 1.Kolors 简介 1.1.什么是Kolors&#xff1f; 开发团队 Kolors 是由快手 Kolors 团队…

组合优化与凸优化 学习笔记4 凸优化问题

优化问题基本定义 假如f(x)是方圆R以内&#xff08;R只要大于0就行&#xff09;最好的一个解 等价问题 就是这种优化函数没啥区别&#xff08;乘了个系数&#xff09;&#xff0c;约束们也就多了个系数的情况&#xff0c;这和原本的显然一样。这是等价的最简单的例子。 归根结…

MES系统如何提升制造企业的运营效率和灵活性

参考拓展&#xff1a;苏州稳联-西门子MES系统-赋能智能制造的核心引擎 制造执行系统(MES)在提升制造企业运营效率和灵活性方面发挥着关键作用。 一、MES系统的基本概念和功能 MES系统是连接企业管理层与生产现场的重要桥梁。它主要负责生产调度、资源管理、质量控制等多个方…

【C++ 基础数学 】2121. 2615相同元素的间隔之和|1760

本文涉及的基础知识点 基础数学 LeetCode2121. 相同元素的间隔之和 难度分&#xff1a;1760 令2165&#xff0c;和此题几乎相等。 给你一个下标从 0 开始、由 n 个整数组成的数组 arr 。 arr 中两个元素的 间隔 定义为它们下标之间的 绝对差 。更正式地&#xff0c;arr[i] 和…

李宏毅2023机器学习HW15-Few-shot Classification

文章目录 LinkTask: Few-shot ClassificationBaselineSimple—transfer learningMedium — FO-MAMLStrong — MAML Link Kaggle Task: Few-shot Classification The Omniglot dataset background set: 30 alphabetsevaluation set: 20 alphabetsProblem setup: 5-way 1-sho…

9/24作业

1. 分文件编译 分什么要分文件编译&#xff1f; 防止主文件过大&#xff0c;不好修改&#xff0c;简化编译流程 1) 分那些文件 头文件&#xff1a;所有需要提前导入的库文件&#xff0c;函数声明 功能函数&#xff1a;所有功能函数的定义 主函数&#xff1a;main函数&…

请不要在TS中使用Function类型

在 TypeScript 中&#xff0c;避免使用 Function 作为类型。Function 代表的是“任意类型的函数”&#xff0c;这会带来类型安全问题。对于绝大多数情况&#xff0c;你可能更希望明确地指定函数的参数和返回值类型。 如果你确实想表达一个可以接收任意数量参数并返回任意类型的…

Kali wireshark抓包

wireshark 查看指定网卡进出流量 构造一个只能显示ICMP数据包的显示过滤器 ARP 同理&#xff0c;显示过滤器会屏蔽所有除了 ARP 请求和回复之外的数据包

力扣 中等 92.反转链表 II

文章目录 题目介绍题解 题目介绍 题解 class Solution {public ListNode reverseBetween(ListNode head, int left, int right) {// 创建一个哑节点&#xff0c;它的 next 指向头节点&#xff0c;方便处理ListNode dummy new ListNode(0, head);// p0 用于指向反转部分的前一个…

3. 轴指令(omron 机器自动化控制器)——>MC_MoveVelocity

机器自动化控制器——第三章 轴指令 6 MC_MoveVelocity变量▶输入变量▶输出变量▶输入输出变量 功能说明▶指令详情▶时序图▶重启运动指令▶多重启动运动指令▶异常 动作示例▶动作示例▶梯形图▶结构文本(ST) MC_MoveVelocity 使用伺服驱动器的位置控制模式&#xff0c;进行…

聊一下cookie,session,token的区别

cookie cookie是存放在客户端的,主要用于会话管理和用户数据保存;cookie通过http报文的请求头部分发送给服务器,服务器根据cookie就可以获取到里面携带的session id(用于获取服务器中对应的session数据),因为http是无状态协议,我们通常就是通过cookie去维护状态的 cookie是在…