1.首先写一个上传文件的页面,命名为upload.html 放到classpath 目录下:
下面的action 对应controller 中的requestmapping, name 对应的是文件上传的参数。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传Demo</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
选择文件 <input type="file" name="fileName"></input>
<br/>
<input type="submit"></input>
</form>
</body>
</html>
2.写一个controller:
package com.cz.controller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@RequestMapping("/upload")
public Map<String, Object> fileUpload(MultipartFile fileName) throws IllegalStateException, IOException{
fileName.transferTo(new File("/Users/tim/spring/cn.cz.fileupload/src/main/resources/static/"+ fileName.getOriginalFilename()));
Map<String, Object> map = new HashMap<String, Object>();
map.put("msg", "success");
return map;
}
}
启动类:
package com.cz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
点击提交后:
文件被上传到:
这里面,如果上传较大文件会报错如下:
context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException: the request was rejected because its size (100522948) exceeds the configured maximum (10485760)] with root cause
org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException: the request was rejected because its size (100522948) exceeds the configured maximum (10485760)
针对这个问题需要修改:
application.properties
spring.servlet.multipart.max-file-size=1024MB
spring.servlet.multipart.max-request-size=1024MB
其中:spring.servlet.multipart.max-file-size=1024MB 代表单次上传支持的最大文件大小
spring.servlet.multipart.max-request-size=1024MB 代表上传文件的总大小。
来源:CSDN
作者:不二村长
链接:https://blog.csdn.net/timeve/article/details/104467028