java 简单的spring boot 服务器和文件上传接口(exceeds its maximum报错)

服务器项目目录结构

  • controller 接口
  • service 接口调用的业务代码
  • mapper(包含xxxMapper.java 和 xxxMapper.xml) sql语句和它的映射方法
  • entity 或者 model 实体类 (包含各种TO和DO,TO用于接口交互的数据,DO用于数据库交互的数据)
  • util 工具类
  • general 或者 constant 常量或者通用类
    1. 必然包含ResultContant.java,用于请求响应的识别code
    2. BaseResponse.java (含有code/msg/data字段),code表示响应的识别码,msg表示响应的提示,data表示请求响应的泛型数据
    3. ServiceResult.java 适用于业务的返回,类似于BaseResponse,不可混用
    4. SpringApplicationContext.java 获取spring容器的上下文,适用于那些想要直接拿容器内容的地方(待研究)

Controller

import org.slf4j.Logger
import org.slf4j.LoggerFactory

@RestController
@RequestMapping("/")
@CrossOrigin(origins = "*")
public class AppController {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(AppController.class);
	
	@Autowired
	private XxxService xxxService;
	
	...
}

fileUpload接口

针对同名文件的上传,可以做一点工作区分,而不是通过改变文件名来避免,待研究

@Value("${file-upload.server-file-path}")
private String serverFilePath;

// 多个文件的上传待研究
@ResponseBody
@RequestMapping(value = "fileUpload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public BaseResponse fileUpload(HttpServletRequest request, MultipartFile file) {
	BaseResponse response = new BaseResponse(ResultConstant.SUCCESS, "success");
	
	string path = request.getSession.getServletContext().getRealPath("/file");
	File targetPath = new File(path);	// 本地真实地址,用于存放文件
	if (!targetPath.exists()) {
		targetPath.mkdirs();
	}
	String filename = file.getOriginalFilename();
	String uuid = UUID.randomUUID().toString().replace("_", "");
	filename = uuid + "_" + filename;
	try {
		// 上传
		file.transferTo(new File(path, filename));
		JSONObject obj = new JSONObject();
		// serverFilePath是访问地址,它和存放地址都可以配置,(上文存放地址对应的访问地址: http://localhost:port/file/xxx.xxx),此处的port是服务器的端口,(这里最好使用一个外部的web服务器)
		obj.put("url", serverFilePath + filename);
		response.setData(obj);
	} catch(IOException e) {
		e.printStackTrace();
		response.setCode(ResultConstant.FAIL);
	}
	return response;
}

如何测试文件上传

  1. postman: 接口 + POST + Body(form-data + key设置为file, 类型也是file + value选择文件) 点击Send即可
  2. 前端的 input type=file:
function fileUpload(files) {
	let formData = new FormData();
	formData.append("file", files[0]);
	axios({		// 也可以使用其他发送请求的方式
		method: "POST",
		url: ...,
		timeout: ...,
		data: formData	//注意,不需要使用{file: ..}形式,也不需要headers属性
	}).then((response) => {
		
	}).catch((error) => {
	
	})
}

文件上传报错信息:

org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.

  • 原因: 上传文件过大
  • 解决办法: application.yml 或 application.properties中添加配置
// application.properties
spring.servlet.multipart.max-file-size = 10MB  
spring.servlet.multipart.max-request-size=10MB
// application.yml
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

图片压缩上传

  • 安装依赖: net.coobird thumbnailator 0.4.14
<dependency>
	 <groupId>net.coobird</groupId>
	 <artifactId>thumbnailator</artifactId>
	 <version>0.4.14</version>
</dependency>
  • 使用:
Thumbnails.of(multipartFile.getInputStream()) 	// multipartFile是接口的对象参数
	.scale(1f) 	// 图片缩放比例
	.outputQuality(0.25f) 	// 图片压缩比例
	.toFile(targetFile);	// 图片的目标存储File

简单的用户信息数据库

CREATE TABLE `user` (
	`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	`gmt_create` datetime NOT NULL
	`gmt_modified` datetime NOT NULL
	`name` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '昵称',
	`head_image_url` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '头像地址',
	PRIMARY KEY(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=COMPACT;
  1. 属性名、表名等一定要小写,可以使用下划线分割
  2. 使用 utf8mb4 和 utf8mb4_bin
  3. 每个表都需要有 id、gmt_create、gmt_modified
    参照 阿里巴巴Java开发手册

SpringApplicationContext.java 具体的适应场景待研究

@Component("springApplicationContext")
public class SpringApplicationContext implements ApplicationContextAware {
	private static ApplicationContext APPLICATION_CONTEXT;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// 防止走两遍
		if (applicationContext.getParent() == null) {
			SpringApplicationContext.APPLICATION_CONTEXT = applicationContext;
		}
	}
	
	public static ApplicationContext getApplicationContext() {
		return APPLICATION_CONTEXT;
	}
	
	/**从静态变量applicationContext中取得bean,自动转型为所赋值对象的类型*/
	public static <T> T getBean(String name) {
		checkApplicationContext();
		return (T)APPLICATION_CONTEXT.getBean(name);
	}
	
	/**从静态变量applicationContext中取得bean,自动转型为所赋值对象的类型*/
	public static <T> T getBean(Class<T> clazz) {
		checkApplicationContext();
		return (T)APPLICATION_CONTEXT.getBean(clazz);
	}
	
	public static void cleanApplicationContext() {
		APPLICATION_CONTEXT = null;
	}
	
	public static void checkApplicationContext() {
		Assert.notNull(APPLICATION_CONTEXT, "applicationContext未注入,请在applicationContext.xml中定义ContextUtils");
	}
}

使用场景:

Class clazz = METHOD_MAP.get(...);	// 通过Map<Integer, Class>获取相应class
xxx = SpringApplicationContext.getBean(clazz);	// 转成spring 对象
原文地址:https://www.cnblogs.com/nangezi/p/14574032.html