SpringBoot——文件上传

目录

  • 单文件上传

    • 表单上传
    • ajax上传
  • 多文件上传
    • 表单上传
    • ajax上传
  • 文件上传配置
    • 方法一:在配置文件中添加配置
    • 方法二:在启动类中添加Bean配置
  • 踩坑经验

单文件上传

表单上传

1.前端表单

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="提交">
</form>

2.后端接收

    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String format = sdf.format(new Date());
        String realPath = req.getServletContext().getRealPath("/img") + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

ajax上传

1.前端

<div id="result"></div>
<input type="file" id="file">
<input type="button" value="上传" onclick="uploadFile()">

<script>
    function uploadFile() {
        var file = $("#file")[0].files[0];
        var formData = new FormData();
        formData.append("file", file);
        $.ajax({
            type:'post',
            url:'/upload',
            processData:false,
            contentType:false,
            data:formData,
            success:function (msg) {
                $("#result").html(msg);
            }
        })
    }
</script>

2.后端相同

多文件上传

表单上传

1.前端

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">  //此时选择多个文件
    <input type="file" name="file">  //或者使用多个input标签
    <input type="submit" value="提交">
</form>

2.后端

   @PostMapping("/uploads")
    public String uploads(MultipartFile[] files,  //如果使用同一个名称,使用数组接收,如果不是同一名称,定义多个MultipartFile
                          HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String format = sdf.format(new Date());
        String realPath = req.getServletContext().getRealPath("/img") + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        for (MultipartFile file : files) {
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                file.transferTo(new File(folder, newName));
                String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newName;
                System.out.println(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

ajax上传

1.前端

<div id="result"></div>
<input type="file" name="Files" id="Files" multiple="multiple" value="上传Files" />
<input type="button" value="上传" onclick="uploadFile()">
<script>
    function uploadFile() {
        var formData = new FormData();//就像cookie一样用,存入files[i];;数组形式
        var files = document.getElementById("Files").files;
        for (var i = 0; i < files.length ; i++)
            {
                formData.append("files_"+i, files[i]);
            }
        $.ajax({
                url: "/uploads",//请求地址
                dataType: "json",//数据格式
                type: "POST",//请求方式
                async: true,//是否异步请求
                cache: false,//上传文件无需缓存
                contentType: false,//必须
                processData: false,//用于对data参数进行序列化处理 这里必须false
                data: formData,
                success: function (data) {
                }
            })
    }
</script>

2.后端一致

文件上传配置

方法一:在配置文件中添加配置

#静态资源对外暴露的访问路径
file.staticAccessPath=/static/image/**
#文件上传目录(注意Linux和Windows上的目录结构不同)
#file.uploadFolder=/root/uploadFiles/
file.uploadFolder=d://uploadFiles/? ?#特别要注意此位置
#文件大小设置
spring.servlet.multipart.enabled=true  #是否支持 multipart 上传文件
spring.servlet.multipart.max-file-size=30MB ?#设置单个文件的大小
spring.servlet.multipart.max-request-size=100MB  ?#设置总上传的数据大小
spring.servlet.multipart.file-size-threshold=0,支持文件写入磁盘
spring.servlet.multipart.location=,上传文件的临时目录
spring.servlet.multipart.resolve-lazily=false,是否支持 multipart 上传文件时懒加载

方法二:在启动类中添加Bean配置

启动类 或 配置类

  /**
   * 文件上传配置
   * @return
   */
  @Bean
  public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    // 单个文件数据大小
    factory.setMaxFileSize("10240KB"); //KB,MB
    // 设置总上传数据总大小
    factory.setMaxRequestSize("102400KB");
    // 设置文件路径
    factory.setLocation(PropertyUtil.getPropertValueByKey("rootpath"));
    return factory.createMultipartConfig();
  } 

踩坑经验

https://www.jianshu.com/p/d8666f2e698f

原文地址:https://www.cnblogs.com/luckyhui28/p/12348300.html

时间: 2024-07-31 09:58:22

SpringBoot——文件上传的相关文章

springboot 文件上传大小配置

转自:https://blog.csdn.net/shi0299/article/details/69525848 springboot上传文件大小的配置有两种,一种是设置在配置文件里只有两行代码,一种是加个Bean. 第一种: application.properties中添加 spring.http.multipart.maxFileSize=10Mb spring.http.multipart.maxRequestSize=10Mb maxFileSize 是单个文件大小, maxRequ

SpringBoot 文件上传、下载、设置大小

本文使用SpringBoot的版本为2.0.3.RELEASE 1.上传单个文件 ①html对应的提交表单 <form action="uploadFile" method="post" enctype="multipart/form-data"> <p>选择文件: <input type="file" name="fileName"/></p> <p&

SpringBoot学习6:springboot文件上传

1.编写页面uploadFile.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> <form action="uploadFile" method="post" enct

springboot文件上传报错

异常信息: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request;nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.1978174608501890996.8083/work/Tomcat/localhost/pmap] is not vali

springboot文件上传: 单个文件上传 和 多个文件上传

单个文件上传 //文件上传统一处理 @RequestMapping(value = "/upload",method=RequestMethod.POST) @ResponseBody public WangEditor uploadFile( @RequestParam("myFile") MultipartFile multipartFile, HttpServletRequest request) { try { /*// 获取项目路径 String real

SpringBoot文件上传(MVC情况和webFlux情况)

MVC情况 引入依赖 <?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/PO

springboot 文件上传下载

关键点: 1,使用 POST 请求2,consumes=MediaType.MULTIPART_FROM_DATA_VALUE3,@RequestParm 里面的字符串和前端 input 控件的 name 值一致 上传文件示例: @PostMapping(value="/photos", consumes=MediaType.MULTIPART_FROM_DATA_VALUE) public void addPhoto(@RequestParm("photo") M

SpringBoot文件上传

先建工程 只勾选web和freemarker模板 最后 先看一下最终目录结构 先修改pom文件,加入common-io依赖 然后修改Application.yml文件 spring: freemarker: templateLoaderPath: classpath:/templates/ content-type: text/html charset: UTF-8 suffix: .ftl 然后新建一个controller package com.example.demo.controller

springBoot(3)---目录结构,文件上传

目录结构,文件上传 一.目录结构 1.目录讲解 src/main/java:存放代码      src/main/resources                   static: 存放静态文件,比如 css.js.image, (访问方式 http://localhost:8080/js/main.js)                   templates:存放静态页面jsp,html,tpl                   config:存放配置文件,application.pr