JavaWeb之上传文件

上传文件

对于很多网站都会遇到一些文件上传的功能,比如上传头像,上传excel等,而基于表单的提交对于传送二进制数据有些力不从心,因为表单数据是拼接在url上的,而url本身是有长度限制的,所以出现了multipart格式的数据,将一个表单拆分为多个部分(part),每个部分对应一个输入域

css 复制代码
------WebKitFormBoundaryBlo55fOFFMVhQ5pv
Content-Disposition: form-data; name="file"; filename="timg.jpeg"
Content-Type: image/jpeg


------WebKitFormBoundaryBlo55fOFFMVhQ5pv--
html 复制代码
<!-- 上传文件一定要使用post请求
		 enctype需要设置为multipart/form-data
     input标签的type类型设为file
-->
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">

form表单的编码格式

  • application/x-www-form-urlencoded 默认 在发送前编码所有字符
  • multipart/form-data 不对字符编码,二进制
  • text/plain 空格转换为+号,但不对特殊字符编码

使用读取流的方式来读取太过于麻烦 request.getInputStream() 获取到的是整个请求体,需要解析各个字段和分隔 解析multipart/form-data比较复杂 可以使用外部依赖包 commons-fileupload.jar 依赖于 commons-io.jar

xml 复制代码
<!-- 文件上传 -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.4</version>
</dependency>

commons-fileupload解析请求

commons-fileupload解析请求会将请求解析成FileItem集合,无论是文本域还是文件域,通过使用FileItem.isFormField()来判断是不是一个表单域,对于表单域,有以下方法(item.getFieldName item.getString) ;对于非表单域 ,有以下方法(item.getFieldName item.getName item.getContentType item.isImemory item.getSize item.getInputStream)

java 复制代码
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //先判断上传的的数据是文件
        if ( ServletFileUpload.isMultipartContent(request) ) {
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

            try {
                // 解析 上传的数据,得到每一个表单项 FiltItem
                List<FileItem> list = servletFileUpload.parseRequest(request);

                for (FileItem fileItem : list) {

                    // 是普通表单项
                    if ( fileItem.isFormField() ) {
                        String fieldName = fileItem.getFieldName(); // 表单项的name属性值
                        String value = fileItem.getString("UTF-8"); //表单项的value属性值 

                    } else {
                        //是上传的文件
                        String name = fileItem.getFieldName();
                        String fieldName = fileItem.getName();

                        // 将数据写到指定的位置
                        fileItem.write(new File( "/var/lib/upload/" + fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

zhhll.icu/2021/javawe...

本文由mdnice多平台发布

相关推荐
开心香辣派小星1 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn2 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
摆烂z2 小时前
Docker与Jib(maven插件版)实战
java
RainbowSea2 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端
笨手笨脚の2 小时前
Spring Core常见错误及解决方案
java·后端·spring
奶油松果2 小时前
Springboot自动装配 - redis和redission
java·spring boot·redis
霍夫曼3 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
VX:Fegn08953 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
荔枝hu3 小时前
springboot和shiro组合引入SseEmitter的一些坑
java·spring boot·后端·sseeitter
老华带你飞3 小时前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端