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/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

前台(两个js框架自行下载)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            height: 100%;
            min-height: 100%;
        }

        .header {
            padding: 1px;
            position: relative;
            left: 0;
            top: 0;
            width: 100%;
            height: 70px;
            background-color: #4E3384;
            color: #c7acff;
        }

        .header h2 {
            text-align: center;
        }

        .header a {
            display: block;
            position: absolute;
            top: 18px;
            right: 15px;
            padding: 8px 15px;
            background-color: #a27bf1;
            color: #fff;
            border-radius: 3px;
            text-decoration: none;
        }

        .container {
            min-height: 100%;
        }

        .main {
            max-width: 1200px;
            margin: 30px auto;
            text-align: center;
        }

        .file-wrap {
            position: relative;
            padding: 8px 10px;
            background-color: #ad0660;
            color: #fff;
            text-decoration: none;
            font-size: 14px;
            border-radius: 3px;
            margin: 60px 25px;
            display: inline-block;
        }

        .file-wrap:hover {
            background-color: #d80b7a;
        }

        .file-input {
            font-size: 0;
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
            opacity: 0;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h2>文件上传</h2>
    </div>
    <div class="main">
        <a href="javascript:;" class="file-wrap">单文件上传
            <input type="file" id="singleFile" name="singleFile" class="file-input">
        </a>
        <a href="javascript:;" class="file-wrap">多文件上传
            <input type="file" id="multiFile" name="multiFile" class="file-input" multiple>
        </a>
        <div id="imgDiv"></div>
    </div>
</div>
<script th:src="@{js/jquery-3.3.1.min.js}"></script>
<script th:src="@{js/ajaxfileupload.js}"></script>
<script>

    $(document).on(‘change‘, ‘#singleFile‘, function () {
        $.ajaxFileUpload({
            url: ‘/upload/single‘, // 用于文件上传的服务器端请求地址
            secureuri: false, // 是否需要安全协议,一般设置为false
            fileElementId: ‘singleFile‘, // 文件上传域的ID
            dataType: ‘json‘, // 返回值类型 一般设置为json
            // 服务器成功响应处理函数
            success: function (data, status) {
                alert(data.msg);
                if (data.code == 1){
                    $(‘#imgDiv‘).append($(‘<img src="‘+ data.data +‘">‘));
                }
            },
            // 服务器响应失败处理函数
            error: function (data, status, e) {
                alert(e);
            }
        });
        $(‘#singleFile‘).val(‘‘);
    })

    $(document).on(‘change‘, ‘#multiFile‘, function () {
        $.ajaxFileUpload({
            url: ‘/upload/multi‘, // 用于文件上传的服务器端请求地址
            secureuri: false, // 是否需要安全协议,一般设置为false
            fileElementId: ‘multiFile‘, // 文件上传域的ID
            dataType: ‘json‘, // 返回值类型 一般设置为json
            // 服务器成功响应处理函数
            success: function (data, status) {
                alert(data.msg);
                if (data.code == 1){
                    for (var i = 0; i < data.data.length; i++){
                        $(‘#imgDiv‘).append($(‘<img src="‘+ data.data[i] +‘">‘));
                    }
                }
            },
            // 服务器响应失败处理函数
            error: function (data, status, e) {
                alert(e);
            }
        });
        $(‘#multiFile‘).val(‘‘);
    })

</script>
</body>
</html>

最后是Java代码

这个是通用的返回结果

package com.example.demo;

import lombok.Data;

@Data
public class BaseResponse<T> {

    private T data;
    private int code = 1;   // 0-false;1-true;默认1
    private String msg = "success";
}

下面是核心上传代码(一个单文件上传,一个多文件上传)

package com.example.demo;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/upload")
public class FileController {

    @PostMapping("/single")
    public BaseResponse<String> single(@RequestParam("singleFile") MultipartFile file, HttpServletRequest req) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = new Date().getTime() + "";
        String fileSize = FileUtils.byteCountToDisplaySize(file.getSize());
        System.out.println("文件名:" + fileName);
        System.out.println("文件大小:" + fileSize);
        String path = req.getServletContext().getRealPath("/MyFiles/"); // 保存在项目运行目录下的MyFiles文件夹
        File targetFile = new File(path + newFileName + fileType);
        FileUtils.copyInputStreamToFile(file.getInputStream(), targetFile);
        String imgPath = targetFile.getPath();
        System.out.println("保存路径:" + imgPath);
//        String url = req.getScheme() + "://" + req.getServerName() + req.getContextPath() +
//                "/MyFiles/" + newFileName + fileType;
        String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() +
                "/MyFiles/" + newFileName + fileType;
        System.out.println("URL:" + url);
        BaseResponse<String> response = new BaseResponse<>();
        response.setData(url);
        return response;
    }

    @PostMapping("/multi")
    public BaseResponse<List<String>> multi(@RequestParam("multiFile") MultipartFile[] files, HttpServletRequest req) throws IOException {
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : files){
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = new Date().getTime() + "";
            String fileSize = FileUtils.byteCountToDisplaySize(file.getSize());
            System.out.println("文件名:" + fileName);
            System.out.println("文件大小:" + fileSize);
            String path = req.getServletContext().getRealPath("/MyFiles/");
            File targetFile = new File(path + newFileName + fileType);
            FileUtils.copyInputStreamToFile(file.getInputStream(), targetFile);
            String imgPath = targetFile.getPath();
            System.out.println("保存路径:" + imgPath);
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() +
                    "/MyFiles/" + newFileName + fileType;
            System.out.println("URL:" + url);
            urls.add(url);
            System.out.println("=======================================");
        }

        BaseResponse<List<String>> response = new BaseResponse<>();
        response.setData(urls);
        return response;
    }
}

最后你可以配置上传文件大小,在application.properties

spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=10MB

启动项目:http://localhost:8080/

后台打印:

WebFlux情况(Spring5的新产品)

原文地址:https://www.cnblogs.com/LUA123/p/10518272.html

时间: 2024-08-30 16:54:47

SpringBoot文件上传(MVC情况和webFlux情况)的相关文章

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 文件上传大小配置

转自: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文件上传: 单个文件上传 和 多个文件上传

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

SpringBoot——文件上传

目录 单文件上传 表单上传 ajax上传 多文件上传 表单上传 ajax上传 文件上传配置 方法一:在配置文件中添加配置 方法二:在启动类中添加Bean配置 踩坑经验 单文件上传 表单上传 1.前端表单 <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file&q

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

spring-boot 参数长度、文件上传大小限制问题

spring boot 设置tomcat post参数限制 1.外置tomcat: 这个简单,直接在server.xml里面修改这句话: <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" maxPostSize="0"/> 没错就是修改这里的maxPostSize的值,