前言
本文是一篇由前端发起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;
}
}