springboot入门到精通(十)springboot文件上传

导读:本篇文章讲解 springboot入门到精通(十)springboot文件上传,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

springboot文件上传

目录

1介绍
2springboot初体验
3springboot集成jsp
4springboot属性注入
5springboot集成mybatis
6springboot集成lombok
7springboot集成logback日志
8springboot开启全局热部署
9springboot面向切面编程
10springboot文件上传
11springboot文件下载
12springboot自定义拦截器
13springboot打成war包发布
14springboot打成jar包发布
15springboot自定义banner
16springboot配置文件拆分

入门示例

  1. springboot自带上传功能,可以不用添加额外依赖。
  2. 准备上传页面upload.jsp,提供form表单,post请求,enctype=“multipart/form-data”
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>上传页面</title>
</head>
<body>
欢迎使用上传页面
<form action="${basePath}Test/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file1">
    <input type="submit" value="上传文件">
</form>
</body>
</html>
  1. 创建一个上传类进行测试
@Controller
@RequestMapping("Test")
public class TestController {
    @RequestMapping("upload")
    public String uploadFile(MultipartFile file1){
        System.out.println("变量名:"+file1.getName());
        System.out.println("文件名:"+file1.getOriginalFilename());
        System.out.println("文件类型:"+file1.getContentType());
        System.out.println("文件大小:"+file1.getSize());
        return "redirect:/upload.jsp";
    }
}
  1. 在浏览器运行http://localhost:8088/moyundong/upload.jsp
  2. 在页面选择一个文件,然后点击“上传文件”按钮
  3. 控制台会打印如下的文件信息
文件名:file1
文件名:springboot4-1.png
文件类型:image/png
文件大小:34648

::: warning 注意
本例需要注意的是

  1. 使用form表单上传,提交方式是post,必须加上 enctype=“multipart/form-data”
  2. <input type="file" name="file1"> 的那么必须与uploadFile(MultipartFile file1)中一致,本例中都是file1
  3. 这个示例只是把文件上传上来,并没有做任何处理,没有把他放到一个指定的地方
    :::

文件放到指定地方

  1. 直接指定到某个文件里面,如果明确知道要保存文件的路径和格式,使用file1.transferTo(new File("d:/uploadtest/aa.png"));方法
    直接把file1文件放到路径d:/uploadtest/aa.png的文件里面。这种方式用的很少
  2. 把文件统一放到项目内一个特定的目录
  • 在项目webapp文件夹下创建upload文件夹,用来存放上传的文件
  • 根据相对路径获取upload文件夹的绝对路径, String realFileRootPath = request.getSession().getServletContext().getRealPath(“upload”);
  • 使用file1.transferTo(new File(realFileRootPath,file1.getOriginalFilename()));把file1文件放到upload文件夹下,如果想改变文件的名字,在
    new File的第二个参数修改就行。

具体代码如下:

@Controller
@RequestMapping("Test")
public class TestController {
    @RequestMapping("upload")
    public String uploadFile(MultipartFile file1, HttpServletRequest request){
        System.out.println("变量名:"+file1.getName());
        System.out.println("文件名:"+file1.getOriginalFilename());
        System.out.println("文件类型:"+file1.getContentType());
        System.out.println("文件大小:"+file1.getSize());
        //根据相对路径获取upload文件夹的绝对路径
        String realFileRootPath = request.getSession().getServletContext().getRealPath("upload");
        //处理上传操作
        try {
            file1.transferTo(new File(realFileRootPath,file1.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/upload.jsp";
    }
}

自定义上传文件大小

直接在application.yml文件里面添加如下配置就可以控制上传文件的大小。

spring:
  servlet:
    multipart:
      max-request-size: 10MB #控制请求上传文件大小(总数据的大小),默认值10MB
      max-file-size: 1MB # 单个文件上传大小(单个数据的大小),默认值1MB

项目应用

在实际项目中,我们经常是按照日期创建一个文件夹,每天上传的文件都放到该文件夹,上传的文件为了避免名称相同覆盖,所以
文件名前缀都会加上一个uuid,中间加上日期,最后跟上文件类型。

  1. 引入common-upload依赖,里面有很多操作文件的工具,方便我们使用
    <!--操作文件工具类 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>

本例中使用String extension = FilenameUtils.getExtension(file1.getOriginalFilename());获取了文件的扩展名
2. 示例代码如下,里面有注解

@RequestMapping("upload2")
    public String uploadFile2(MultipartFile file1, HttpServletRequest request){
        System.out.println("变量名:"+file1.getName());
        System.out.println("文件名:"+file1.getOriginalFilename());
        System.out.println("文件类型:"+file1.getContentType());
        System.out.println("文件大小:"+file1.getSize());
        //根据相对路径获取upload文件夹的绝对路径
        String realFileRootPath = request.getSession().getServletContext().getRealPath("upload");
        //根据日期生成文件夹
        String dateDirName = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File newDateFile = new File(realFileRootPath,dateDirName);
        if (!newDateFile.exists()){
            newDateFile.mkdirs();
        }
        //使用工具,获取文件后缀
        String extension = FilenameUtils.getExtension(file1.getOriginalFilename());
        String newFileName = UUID.randomUUID().toString().replaceAll("-","") +
                new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(new Date())+"."+extension;
        //处理上传操作
        try {
            file1.transferTo(new File(newDateFile,newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/upload.jsp";
    }

同时上传多个文件

  • 基本原理都是相同的,需要注意的是在jsp文件添加上传文件的时候,name属性要一样。
  • controller里面方法接收参数变为MultipartHttpServletRequest multipartRequest
  1. jsp添加如下代码
<form action="${basePath}Test/upload3" 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>
  1. controller代码如下:
@RequestMapping("upload3")
    public String uploadFile3(MultipartHttpServletRequest multipartRequest){
        //根据相对路径获取upload文件夹的绝对路径
        String realFileRootPath = multipartRequest.getSession().getServletContext().getRealPath("upload");
        //根据日期生成文件夹
        String dateDirName = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File newDateFile = new File(realFileRootPath,dateDirName);
        if (!newDateFile.exists()){
            newDateFile.mkdirs();
        }
        //获取文件list
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        //循环fileList,获取文件扩展名,自定义文件名称,然后上传文件
        fileList.forEach(multipartFile -> {
            //使用工具,获取文件后缀
            String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
            String newFileName = UUID.randomUUID().toString().replaceAll("-","") +
                    new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(new Date())+"."+extension;
            //处理上传操作
            try {
                multipartFile.transferTo(new File(newDateFile,newFileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return "redirect:/upload.jsp";
    }

本节示例下载地址:java相关demo下载列表

::: warning 注意
在不同的平台,文档显示的效果是不一样的,最佳最全观看地址:springboot文件上传
欢迎大家来博客了解更多内容:java乐园
:::

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

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/13522.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!