一 先搭建一个包含web的springboot项目,后面附上源码。
<?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 https://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.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zhao</groupId>
<artifactId>demoFile</artifactId>
<version>0.1</version>
<packaging>war</packaging>
<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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--打不了包,就导入这个-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二 然后写一个工具类,用来上传文件。
package com.zhao.demo.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @description: 文件上传工具类
* @author: 小赵
* @date: 2021/10/13 16:33
* @version: v1.0
*/
@Component
public class FileUtil {
/**
* 图片上传
* */
public Object uploadImage(MultipartFile file, HttpServletRequest request) {
/**图片保存的绝对路径*/
String realPath = "/space/projects_pro/uploadFile/fileImages/";
/**项目名,打包后的包名*/
String projectName="demoFile-0.1";
/**当天时间*/
Date date=new java.sql.Date(System.currentTimeMillis());
File dir = new File(realPath+"/"+date);
if (!dir.isDirectory()) {//文件目录不存在,就创建一个
dir.mkdirs();
}
String filename = file.getOriginalFilename();
/**
* 获取文件后缀
*/
String suffix= filename.substring(filename.lastIndexOf("."));
/**
* 生成新的文件名
*/
String newName= UUID.randomUUID().toString().replace("-", "")+suffix;
File fileServer = new File(dir, newName);
System.out.println("file文件真实路径:" + fileServer.getAbsolutePath());
//2,实现上传
try{
file.transferTo(fileServer);
}catch (IOException e){
e.printStackTrace();
}
String filePath = request.getScheme()+"://" +
request.getServerName() + ":"
+ request.getServerPort()+"/"+projectName
+ "/uploadFile/fileImages/" + date +"/"+ newName;
//3,返回可供访问的网络路径
Map map=new HashMap();
map.put("file文件真实路径",fileServer.getAbsolutePath());
map.put("返回可供访问的网络路径",filePath);
return map;
}
}
三 配置文件上传的文件大小限制
# 上传文件总的最大值 默认10MB
spring.servlet.multipart.max-request-size=500MB
#单个文件最大值 默认10MB
spring.servlet.multipart.max-file-size=100MB
四 写一个配置类,配置访问的网络路径。
package com.zhao.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.ArrayList;
import java.util.List;
/**
* @description: 配置文件
* @author: 小赵
* @date: 2021/10/13 16:38
* @version: v1.0
*/
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
private String realPath="/space/projects_pro/uploadFile/";
@Override
protected void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
}
/**
* swagger 请求的过滤和图片访问路径
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// addResourceHandler是指你想在url请求的路径
// addResourceLocations是图片存放的真实路径
//设置映射规则,原路径(ResourceLocations)被设置成可以通过映射路径(ip:port/images)来访问,可以设置多个
registry.addResourceHandler("/uploadFile/**").
addResourceLocations("file:" + realPath);
}
/**
* addCorsMappings 跨域请求的过滤
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS")
.allowedOrigins("")//设置跨域访问的域名,如果是,默认都可以访问。
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
/**
* 预请求过滤
*/
private CorsConfiguration addcorsConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
List<String> list = new ArrayList<>();
list.add("*");
corsConfiguration.setAllowedOrigins(list);
/*
// 请求常用的三种配置,*代表允许所有,当时你也可以自定义属性(比如header只能带什么,只能是post方式等等)
*/
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
/**
* 启用配置
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", addcorsConfig());
return new CorsFilter(source);
}
}
最后一步,写一个Controller用来调用文件上传。
package com.zhao.demo.controller;
import com.zhao.demo.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
/**
* @description: 调用工具类的文件上传
* @author: 小赵
* @date: 2021/10/13 16:35
* @version: v1.0
*/
@Controller
public class FileController {
@Autowired
private FileUtil fileUtil;
//produces="application/json;charset=utf-8",设置返回的编码格式
@RequestMapping(value = "/file",produces="application/json;charset=utf-8")
@ResponseBody
//@RequestParam(value = "file") 接收单个参数
public Object file(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
return fileUtil.uploadImage(file,request);
}
@RequestMapping(value = "/show",produces="application/json;charset=utf-8" )
@ResponseBody()
public String show(){
return "测试接口";
}
}
常见问题。
一 上传文件出现的问题。
org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
at org.apache.tomcat.util.http.fileupload.impl.FileItemStreamImpl$1.raiseError(FileItemStreamImpl.java:117) ~[tomcat-embed-core-9.0.53.jar:9.0.53]
at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76) ~[tomcat-embed-core-9.0.53.jar:9.0.53]
at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135) ~[tomcat-embed-core-9.0.53.jar:9.0.53]
at java.io.FilterInputStream.read(FilterInputStream.java:107) ~[na:1.8.0_275]
at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:97) ~[tomcat-embed-core-9.0.53.jar:9.0.53]
解决方案。
出现这个问题,那是因为你上传的文件太大了,默认上传文件的大小是10MB,去配置文件配置一下上传的文件大小就可以了。
# 上传文件总的最大值 默认10MB
spring.servlet.multipart.max-request-size=500MB
#单个文件最大值 默认10MB
spring.servlet.multipart.max-file-size=100MB
二 打包出现的问题。
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources) on project demoFile: Input length = 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
Process finished with exit code 1
解决方案。
打包出现问题了,在pom.xml中增加一个包,加在plugins里面。
<!--打不了包,就导入这个-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
</plugin>
通过Postman调用接口,上传文件。
拿到返回的网络路径直接到浏览器访问即可。
不想敲那就复制,附上源码:赵海辉/demo - 码云 - 开源中国 (gitee.com)