SpringBoot 文件上传

springboot项目中默认开启了文件上传功能,而不需要我们手动像springmvc那样进行设置。

前端页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
    <h1>文件上传</h1>
    <hr>
    <form action="upload" method="post" enctype="multipart/form-data">
        请选择文件:<input type="file" name="attach"/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>


后台Java 

package com.test.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadController {

    private Map<String, Object> result = new HashMap<>();
    
    @RequestMapping("/upload")
    public Map<String, Object> upload(@RequestParam("attach") MultipartFile file) throws Exception, IOException{
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("c:/why/"+file.getOriginalFilename()));
        result.put("success",true);
        return result;
    }
}

 

 

设置文件上传大小,可以在springboot的默认配置文件中配置 application.properties

 

spring.servlet.multipart.max-request-size=100MB
spring.servlet.multipart.max-file-size=200MB

  

注意:

  文件默认大小为10MB

  这两个是需要同时设置的,第一个为单个文件的上传大小,第二个为总的文件上传大小;且单位必须为大写如 MB

 

posted @ 2019-02-01 11:23  wmz2why  阅读(149)  评论(0编辑  收藏  举报