SpringBoot上传文件(使用form)

SpringBoot上传文件(使用form)介绍文件上传是企业开发中最常用的功能。本文主要介绍SpringBoot中使用表单上传时单文件上传和多文件上传的操作方式。maven依赖<dependency><groupId>org.springframework.boot</groupId><artifa…

大家好,又见面了,我是你们的朋友全栈君。

介绍

文件上传是企业开发中最常用的功能。本文主要介绍SpringBoot中使用表单上传时单文件上传和多文件上传的操作方式。
 

 maven依赖

 

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>

 

配置文件

 

spring:
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp

  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB

分别配置jsp的前后缀、上传文件总的最大值和单个文件最大值
 

 

上传文件工具类

 

这里的静态方法executeUpload接收两个参数,分别是服务器储存文件位置和文件对象类。将接收的文件对象转储到服务器目录中。

 


package com.example.fileuploadbyform.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

public  class FileUtil {

    public static void executeUpload(String uploadDir, MultipartFile file) throws Exception{
            //文件后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //文件随机名
            String filename = UUID.randomUUID()+suffix;
            //创建文件对象
            File serverFile = new File(uploadDir + filename);
            //转储文件
            file.transferTo(serverFile);
    }
}

 

 

单文件上传

我们准备一个upload.jsp文件用来上传文件


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

 

在来到controller层新建一个FileUploadController文件
 

@RequestMapping("/oneFile")
    public String index(){
        return "upload";
    }


@RequestMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest req, MultipartFile file){
        try{

            String uploadDir = req.getSession().getServletContext().getRealPath("/")+"upload/";
            File dir = new File(uploadDir);
            if(!dir.exists()){
                dir.mkdir();
            }
            FileUtil.executeUpload(uploadDir,file);
        }catch(Exception e){
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }

 

多文件上传

多文件上传比起单文件上传有所不同的就是对接收的文件数组做了一个循环储存,下面是代码。
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/uploads" method="post" enctype="multipart/form-data">
    文件一<input type="file" name="file">
    文件二<input type="file" name="file">
    文件三<input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>
   @RequestMapping("/twoFile")
    public String index1(){
        return "uploads";
    }

    @RequestMapping("/uploads")
    @ResponseBody
    public String uploads(HttpServletRequest req, MultipartFile[] file){
        try{
            String uploadDir = req.getSession().getServletContext().getRealPath("/")+"upload/";
            File dir = new File(uploadDir);
            if(!dir.exists()){
                dir.mkdir();
            }
            for(int i=0;i<file.length;i++){
                if(file[i] != null){
                    FileUtil.executeUpload(uploadDir,file[i]);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }

易错点

1、调用executeUpload之前要判断文件对象是否为空
2、application.yml文件中要配置上传文件最大限制和单个文件上传限制
3、多文件上传时统一form中input的type为file的name要统一,方便controller层中的MultipartFile数组接收

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/133512.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 图书馆管理系统需求规格说明书

    图书馆管理系统需求规格说明书青院图书馆信息管理系统软件需求规格说明书文档编号 QY LY7 文档信息 图书馆信息管理系统软件需求规格说明书文档类别 管理文档密 nbsp nbsp nbsp nbsp 级 机密版本信息 1 0 建立日期 2014 05 20 nbsp 创 nbsp 建 nbsp 人 审 nbsp 核 nbsp 者 批 nbsp 准 nbsp 人 批准日期 nbsp 编辑软件 Microsoft nbsp Office nbsp 2003 nbsp 中文版 WPS nbsp 文字

    2025年9月2日
    3
  • output device(storage devices)

    dockertheinputdeviceisnotaTTY.Ifyouareusingmintty,tryprefixingthecommandwith’winp解决方法执行命令报错dockerexec-it8ea8a375e686/bin/bashtheinputdeviceisnotaTTY.Ifyouareusingmintty,tryprefixingthecommandwith’winpty’解决方案

    2022年4月13日
    43
  • 使用cdn实现免备案_阿里云备案的域名可以在腾讯云用吗

    使用cdn实现免备案_阿里云备案的域名可以在腾讯云用吗昨晚在QQ群看到的,目前可以白嫖!无视阿里云给你分配的cname地址域名直接解析到发的那些cname地址上面就可以使用了!添加CDN,加速区域选择“全球(不含中国大陆)”,然后把域名解析到阿里云国内CDN节点IP上。注意:知道的人多了或者也许会失效!这是我的网站测试的结果可以访问看一下速度:爱云影视…

    2025年10月23日
    6
  • executescalar mysql_ExecuteScalar()

    executescalar mysql_ExecuteScalar()ExecuteScalar()方法的作用是:执行查询,并返回查询所返回的结果集中第一行的第一列。所有其他的列和行将被忽略。它的返回值时object,若是想判断某条数据在数据库里存不存在便可使用该方法,//sql文privatestringm_str_variationInfo=@”SELECTvariationinfoMngnoFROMsellersandvariationmngtbl…

    2022年6月15日
    30
  • Windows上Nginx的安装教程详解[通俗易懂]

    不要觉得看起来简单就不去做,动手操作是另外一回事,相信我! –阿飞一 背景为了方便本地的开发和验证,于是整理了这一篇Windows上安装Nginx的博文,建议一般学习还是使用Linux,一般正规公司都是在Linux上安装Nginx服务! 本篇内容相对比较简单,如果有Linux上安装过Nginx的伙伴,那么看这一篇应该是比较轻松,而且使用也会很方便!二 下载安装包…

    2022年2月27日
    45
  • 如何将Eclipse设置为中文版[通俗易懂]

    如何将Eclipse设置为中文版[通俗易懂]如何将Eclipse设置为中文版我们知道Eclipse一个开放源代码的、基于Java的可扩展开发平台,不管学习还是工作都是一款不错的集成开发环境(IDE),但是对于一些初学者看到Eclipse上

    2022年5月4日
    67

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号