代码如下:
FileUploadController.java文件
package com.example.uploadFile.uploadFile.controller;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
/**
* 上传文件
* 测试方法:
* 有界面的测试:http://localhost:8050/index.html
* 使用命令:curl -F "file=@文件全名" localhost:8050/upload
* ps.该示例比较简单,没有做IO异常、文件大小、文件非空等处理
* @param file 待上传的文件
* @return 文件在服务器上的绝对路径
* @throws IOException IO异常
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
File fileToSave = new File(file.getOriginalFilename());
FileCopyUtils.copy(bytes, fileToSave);
return fileToSave.getAbsolutePath();
}
}
application.yml文件
server:
port: 8050
#eureka:
# client:
# serviceUrl:
# defaultZone: http://localhost:8761/eureka/
# instance:
# prefer-ip-address: true
spring:
application:
name: microservice-file-upload
servlet:
multipart:
max-file-size: 200MB
max-request-size: 200MB
# http:
# multipart:
# max-file-size: 2000Mb # Max file size,默认1M
# max-request-size: 2500Mb # Max request size,默认10M
index.html页面文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/upload">
File to upload:
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
项目启动后,点击如下链接进行上传文件,
http://localhost:8050/index.html
上传成功后
友情提示:
如果文件很大,会报错如图:
可以根据参考文献中信息来修改配置文件!
参考文献:
Spring Boot 上传文件大小配置–基于2.0.3.RELEASE版本