
文件上传,也称为upload,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。
文件上传在项目中应用非常广泛,我们经常发微博、发微信朋友圈都用到了文件上传功能。
文件上传时,对页面的form表单有如下要求
| 表单属性 | 取值 | 说明 |
|---|---|---|
| method | post | 必须选择post方式提交 |
| enctype | multipart/form-data | 采用multipart格式上传文件 |
| type | file | 使用input的file控件上传 |
- <form method="post" action="/common/upload" enctype="multipart/form-data">
- <input name="myFile" type="file" />
- <input type="submit" value="提交" />
- form>
服务端要接收客户端页面上传的文件,通常都会使用Apache的两个组件:
而Spring框架在spring-web包中对文件上传进行了封装,大大简化了服务端代码,我们只需要在Controller的方法中声明一个MultipartFile类型的参数即可接收上传的文件
例如这样子
- /**
- * 文件上传
- * @param file
- * @return
- */
- @PostMapping("/upload")
- public R
upload(MultipartFile file){ - System.out.println(file);
- return R.success(fileName);
- }
upload.html
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>文件上传title>
-
- <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
- <link rel="stylesheet" href="../../styles/common.css" />
- <link rel="stylesheet" href="../../styles/page.css" />
- head>
- <body>
- <div class="addBrand-container" id="food-add-app">
- <div class="container">
- <el-upload class="avatar-uploader"
- action="/common/upload"
- :show-file-list="false"
- :on-success="handleAvatarSuccess"
- :before-upload="beforeUpload"
- ref="upload">
- <img v-if="imageUrl" :src="imageUrl" class="avatar">img>
- <i v-else class="el-icon-plus avatar-uploader-icon">i>
- el-upload>
- div>
- div>
-
- <script src="../../plugins/vue/vue.js">script>
-
- <script src="../../plugins/element-ui/index.js">script>
-
- <script src="../../plugins/axios/axios.min.js">script>
- <script src="../../js/index.js">script>
- <script>
- new Vue({
- el: '#food-add-app',
- data() {
- return {
- imageUrl: ''
- }
- },
- methods: {
- handleAvatarSuccess (response, file, fileList) {
- this.imageUrl = `/common/download?name=${response.data}`
- },
- beforeUpload (file) {
- if(file){
- const suffix = file.name.split('.')[1]
- const size = file.size / 1024 / 1024 < 2
- if(['png','jpeg','jpg'].indexOf(suffix) < 0){
- this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
- this.$refs.upload.clearFiles()
- return false
- }
- if(!size){
- this.$message.error('上传文件大小不能超过 2MB!')
- return false
- }
- return file
- }
- }
- }
- })
- script>
- body>
- html>
CommonController
- /**
- * 文件上传下载
- */
- @Slf4j
- @RestController
- @RequestMapping("/common")
- public class CommonController {
-
- @Value("${reggie.path}")
- private String basePath;
-
- /**
- * 文件上传
- * @param file
- * @return
- */
- @PostMapping("/upload")
- public R
upLoad(MultipartFile file) { -
- // 原始文件名
- String originalFilename = file.getOriginalFilename();
- // 获取文件类型(jpg、png)
- String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
-
- // 使用UUID重新生成文件名,防止文件名重复
- String fileName = UUID.randomUUID() + suffix;
-
- // 创建目录
- File dir = new File(basePath);
- if(!dir.exists()) {
- dir.mkdirs();
- }
-
- try {
- file.transferTo(new File(basePath + fileName));
- } catch (IOException e) {
- e.printStackTrace();
- }
- return R.success(fileName);
- }
-
- /**
- * 文件下载
- * @param name
- * @param response
- */
- @GetMapping("/download")
- public void downLoad(String name, HttpServletResponse response) {
- try {
- //输入流,通过输入流读取文件内容
- FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
-
- //输出流,通过输出流将文件写回浏览器
- ServletOutputStream outputStream = response.getOutputStream();
-
- response.setContentType("image/jpeg");
-
- int len = 0;
- byte[] bytes = new byte[1024];
- while ((len = fileInputStream.read(bytes)) != -1) {
- outputStream.write(bytes, 0, len);
- outputStream.flush();
- }
-
- //关闭资源
- outputStream.close();
- fileInputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
The valid characters are defined in RFC 7230 and RFC 3986
1、考虑get请求头过大,而tomcat的header缓存区又过小
那只能调整tomcat的header缓存区,在server.xml中的Connector标签中添加maxHttpHeaderSize="81920",你要是觉得不够大,可以暂时性的改成一个特别大的数值。
如果用的是SpringBoot,则可以在application.properties文件中配置【server.tomcat.max-http-header-size=81920】
观测一段时间后,如果还是出现这个报错,那么尝试下一个解决方案。
2、使用https去请求http协议
建议每次打印出请求的地址和信息,使用拦截器在preHandle中打印出request的信息,看看有没有出现这样的情况。
3、终极绝招
有时候吧,看报错时间,都是在凌晨,这个就很奇怪。
如果自己用的是8080端口,不妨改一个端口吧。改端口这个好像没什么科学依据,但确实能解决一部分人的问题。
application.yml
- server:
- port: 8080
- # 考虑get请求头过大,而tomcat的header缓存区又过小
- tomcat:
- max-http-form-post-size: 81920
- spring:
- application:
- name: reggie_take_out
- datasource:
- druid:
- driver-class-name: com.mysql.cj.jdbc.Driver
- url: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
- username: root
- password: 888888
- mybatis-plus:
- configuration:
- # 在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射 !!!
- map-underscore-to-camel-case: true
- log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- global-config:
- db-config:
- id-type: ASSIGN_ID
-
- # 指定上传下载文件的缓存路径
- reggie:
- path: D:\images\