SpringBoot+JQuery+Ajax实现表单数据传输和单文件或多文件的上传

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 关于如何在SpringBoot项目中结合JQuery和Ajax实现表单数据的传输以及单文件或多文件上传的教程。文章提供了完整的前后端示例代码,包括项目的`pom.xml`依赖配置、SpringBoot的启动类`App.java`、静态资源配置`ResourceConfig.java`、配置文件`application.yml`、前端HTML页面(单文件上传和多文件上传加表单内容)以及后端控制器`UserController.java`。文章最后展示了运行结果的截图。

前言

本文是一篇由前端发起JQuery+Ajax异步请求,传输表单和文件数据,后端控制器获取数据的文章。复制粘贴,亲测可用!

一、示例代码

(1)pom.xml

<?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>

    <groupId>org.example</groupId>
    <artifactId>springboot-jwt</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>

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

        <!-- Spring Boot Mybatis -->
        <!-- <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency> -->
        <!-- / Spring Boot Mybatis -->

        <!-- MySQL 连接驱动依赖 -->
        <!--<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>-->
        <!-- / MySQL 连接驱动依赖 -->

        <!-- MSSQL 连接驱动依赖 -->
        <!-- <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency> -->
        <!-- / MSSQL 连接驱动依赖 -->

        <!-- java-jwt -->
        <!-- <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.8.1</version>
        </dependency> -->
        <!-- / java-jwt -->

        <!-- jjwt -->
        <!-- <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency> -->
        <!-- / jjwt -->

        <!-- lombok -->
        <!-- <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency> -->
        <!-- / lombok -->

        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>

        <!-- thymeleaf前端模板赋值框架 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- / thymeleaf前端模板赋值框架 -->

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

    </dependencies>

</project>

(2)App.java

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.zhiquan.mapper")
@SpringBootApplication
public class App {
   
   
    public static void main(String[] args) {
   
   
        SpringApplication.run(App.class,args);
    }
}

(3)ResourceConfig.java

package com.zhiquan.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class ResourceConfig extends WebMvcConfigurationSupport {
   
   
    /**
     * 配置静态访问资源,在resources目录新建static子目录,所有静态文件如:css、js、font等存于此
     * @param registry
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
   
   
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

(4)application.yml

server:
  port: 8088

spring:
  thymeleaf:
    prefix:
      classpath: /templates           # 访问templates下的html文件需要配置模板映射,在resources目录新建templates子目录以及xxx等子目录,然后创建html,如:resources/templates/xxx/yyy.html
    cache: false                      # 开发时关闭缓存,不然没法看到实时页面
  datasource:
#    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
#    driverClassName: com.mysql.jdbc.Driver
#    username: root
#    password:
    url: jdbc:sqlserver://99.99.99.99:1433;databaseName=AIOWFILE
    username: root
    password: 
  servlet:
    multipart:
      max-file-size: 5MB              #设置单个文件的最大值
      max-request-size: 15MB          #设置单次请求的所有文件的最大值

(5)uploadSingleFile.html(单文件上传)

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <p>单文件上传</p>
    <p><input id="cert" type="file" /></p>
    <p><input type="button" value="上传" onclick="submit();" /></p>
</body>
<script>
    function submit(){
        var formData = new FormData();
        formData.append("file", $("#cert")[0].files[0]);

        console.log(formData);

        $.ajax({
            type: "POST",
            url: '/uploadSingleFile',
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                alert(data);
            }
        });
    }
</script>
</html>

(6)uploadMultiFile.html(多文件上传 + 表单内容)

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <p>多文件上传 + 表单内容</p>
    <p><input id="cert" type="file" /></p>
    <p><input id="attachment1" type="file" /></p>
    <p><input id="attachment2" type="file" /></p>
    <p><input id="token" type="hidden" value="ka8912kas62ghk236a5adh32s0923lsd"/></p>
    <p><input id="title" type="text" placeholder="标题"/></p>
    <p><input id="content" type="text" placeholder="内容"/></p>
    <p><input type="button" value="上传" onclick="submit();" /></p>
</body>
<script>
    function submit(){
        var formData = new FormData();

        formData.append("file", $("#cert")[0].files[0]);
        formData.append("file", $("#attachment1")[0].files[0]);
        formData.append("file", $("#attachment2")[0].files[0]);
        formData.append("text", $("#title").val());
        formData.append("text", $("#content").val());
        formData.append("hidden", $("#token").val());

        console.log(formData);

        $.ajax({
            type: "POST",
            url: '/uploadMultiFile',
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function (data) {
                console.log(data.msg);
                alert(data.msg);
            },
            error: function (e) {
                console.log(e);
                alert(e);
            }
        });
    }
</script>
</html>

(7)UserController.java

package com.zhiquan.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhiquan.entity.CommonFile;
import com.zhiquan.entity.User;
import com.zhiquan.service.UserService;
import com.zhiquan.utils.JwtUtils;
import com.zhiquan.vo.Msg;
import com.zhiquan.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Controller
public class UserController {
   
   
    @Autowired
    private UserService UserService;

    /**
     * 单文件上传页面
     * @return
     */
    @GetMapping(value = "/uploadSingleFile")
    public String uploadSingleFile(){
   
   
        return "/home/uploadSingleFile";
    }

    /**
     * 多文件上传页面
     */
    @GetMapping(value = "/uploadMultiFile")
    public String uploadMultiFile(){
   
   
        return "/home/uploadMultiFile";
    }


    /**
     * 单文件上传处理
     */
    @PostMapping(value = "/uploadSingleFile")
    @ResponseBody
    public String uploadSingleFile(@RequestParam("file") MultipartFile file) {
   
   
        // 文件处理
        String fileName = file.getOriginalFilename();
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
        //String filePath = "src/main/resources/static/files/";
        String filePath = "D:\\UploadedFile\\";
        File targetFile = new File(filePath);
        if(!targetFile.exists()) {
   
   
            targetFile.mkdirs();
        }

        try {
   
   
            Timestamp ts1 = new Timestamp((new Date("2020/09/16 17:18:42")).getTime());
            Timestamp ts2 = new Timestamp((new Date()).getTime());
            CommonFile commonFile = new CommonFile();
            commonFile.setSubPath("/20200916-171842-123456");
            commonFile.setFileName(file.getOriginalFilename());
            commonFile.setFileExtension(fileExtension);
            commonFile.setCreationTime(ts1);
            commonFile.setModificationTime(ts2);
            commonFile.setAppendix("NULL");
            commonFile.setFileSize((int) file.getSize());
            commonFile.setFileImage(file.getBytes());
            System.out.println(commonFile);

            // 文件存入数据库
            try {
   
   
                UserService.saveCommonFile(commonFile);
                System.out.println("文件存入MSSQL数据库成功!");
            } catch (Exception e){
   
   
                System.out.println("文件存入失败!");
            }

            // 文件存到服务器
            try {
   
   
                FileOutputStream out = null;
                out = new FileOutputStream(filePath + fileName);
                out.write(file.getBytes());
                out.flush();
                out.close();
                System.out.println("文件写入成功!");
            } catch (Exception e){
   
   
                System.out.println("文件写入失败!");
            }

            return "ok";
        } catch (Exception e) {
   
   
            return "no";
        }
    }

    /**
     * 多文件上传处理
     */
    @PostMapping(value = "/uploadMultiFile")
    @ResponseBody
    public JSONObject uploadMultiFile(@RequestParam("file") MultipartFile[] files,@RequestParam("text") String text,@RequestParam("hidden") String token) {
   
   
        System.out.println(text);
        System.out.println(token);

        JSONObject jsonObject = new JSONObject();

        try{
   
   
            if (files.length > 0){
   
   
                for (MultipartFile file:files) {
   
   
                    System.out.println(file.getOriginalFilename());

                    // 文件处理
                    String fileName = file.getOriginalFilename();
                    String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
                    String filePath = "D:\\UploadedFile\\";
                    File targetFile = new File(filePath);
                    if(!targetFile.exists()) {
   
   
                        targetFile.mkdirs();
                    }

                    // 文件存到服务器
                    try {
   
   
                        FileOutputStream out = null;
                        out = new FileOutputStream(filePath + fileName);
                        out.write(file.getBytes());
                        out.flush();
                        out.close();
                        System.out.println("文件写入成功!");
                    } catch (Exception e){
   
   
                        System.out.println("文件写入失败!");
                    }
                }
            }
            jsonObject.put("msg","ok");

        }catch (Exception e){
   
   
            jsonObject.put("msg","no");
        }
        return jsonObject;
    }
}

二、运行结果

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
12天前
|
前端开发 JavaScript 数据处理
JQuery 拦截请求 | Ajax 请求拦截
【10月更文挑战第4天】
32 1
|
26天前
|
前端开发 Java easyexcel
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
28 6
|
26天前
|
JSON 前端开发 JavaScript
jQuery AJAX 方法
jQuery AJAX 方法
28 1
|
28天前
|
JSON JavaScript 前端开发
Jquery常用操作汇总,dom操作,ajax请求
本文汇总了jQuery的一些常用操作,包括DOM元素的选择、添加、移除,表单操作,以及如何使用jQuery发送Ajax请求,涵盖了GET、POST请求和文件上传等常见场景。
|
29天前
|
XML 前端开发 JavaScript
php中Ajax的简单使用,登录表单调用Ajax判断是否正确登录利用layer.msg进行提示
本文介绍了在PHP中如何使用Ajax进行登录表单的数据提交,并利用jQuery的$.post()方法与后端通信,以及使用layer.msg进行前端提示。
php中Ajax的简单使用,登录表单调用Ajax判断是否正确登录利用layer.msg进行提示
|
29天前
|
XML JSON Java
springboot文件上传,单文件上传和多文件上传,以及数据遍历和回显
本文介绍了在Spring Boot中如何实现文件上传,包括单文件和多文件上传的实现,文件上传的表单页面创建,接收上传文件的Controller层代码编写,以及上传成功后如何在页面上遍历并显示上传的文件。同时,还涉及了`MultipartFile`类的使用和`@RequestPart`注解,以及在`application.properties`中配置文件上传的相关参数。
springboot文件上传,单文件上传和多文件上传,以及数据遍历和回显
|
15天前
|
移动开发 JSON 数据可视化
精选八款包括可视化CMS,jquery可视化表单,vue可视化拖拉,react可视化源码
精选八款包括可视化CMS,jquery可视化表单,vue可视化拖拉,react可视化源码
36 0
|
1月前
|
JSON 前端开发 JavaScript
jQuery AJAX 方法
jQuery AJAX 方法
18 1
|
2月前
|
JSON JavaScript 前端开发
基于SpringBoot + Vue实现单个文件上传(带上Token和其它表单信息)的前后端完整过程
本文介绍了在SpringBoot + Vue项目中实现单个文件上传的同时携带Token和其它表单信息的前后端完整流程,包括后端SpringBoot的文件上传处理和前端Vue使用FormData进行表单数据和文件的上传。
192 0
基于SpringBoot + Vue实现单个文件上传(带上Token和其它表单信息)的前后端完整过程
|
2月前
|
Devops 持续交付 测试技术
JSF遇上DevOps:开发流程将迎巨变?一篇文章带你领略高效协同的魅力!
【8月更文挑战第31天】本文探讨了如何在JavaServer Faces(JSF)开发中融入DevOps文化,通过持续集成与部署、自动化测试、监控与日志记录及反馈机制,提升软件交付速度与质量。文中详细介绍了使用Jenkins进行自动化部署、JUnit与Selenium进行自动化测试、ELK Stack进行日志监控的具体方法,并强调了持续改进的重要性。
34 0