springboot文件上傳

再上傳文件時,首先要注意的是application.properties配置文件html

在老版本的基礎上新增長了servlet,如今的寫法是:java

#設置單個文件上傳大小
spring.servlet.multipart.max-file-size=200MB
#設置上傳文件的總容量
spring.servlet.multipart.max-request-size=200MB

可是官網上面是:web

spring.http.multipart.max-file-size=1MB # Max file size. 
spring.http.multipart.max-request-size=10MB # Max request size.

文件上傳源碼:spring

package com.example.springboot2.controller;

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

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

    /**
     * springboot文件上傳
     */
@RestController
public class FileUploadController {
    /**
     * 處理文件上傳
     * @param filename
     * @return
     * @throws Exception
     */
    @RequestMapping("/fileUploadController")
    public Map<String,Object> fileUpload(MultipartFile filename) throws Exception{
        System.out.println(filename.getOriginalFilename());
        filename.transferTo(new File("E:/aaaa/"+filename.getOriginalFilename()));
        Map<String,Object> map=new HashMap<>();
        map.put("message","ok");
        return map;
    }
}

application.properties配置文件:
#設置單個文件上傳大小
spring.servlet.multipart.max-file-size=200MB
#設置上傳文件的總容量
spring.servlet.multipart.max-request-size=200MB

App啓動類:
package com.example.springboot2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot2Application {

	public static void main(String[] args) {

		SpringApplication.run(Springboot2Application.class, args);
	}

}
 HTML代碼:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上傳</title>
</head>
<body>
<form action="fileUploadController" method="post" enctype="multipart/form-data">
    文件上傳:<input type="file" name="filename"/>
    <input type="submit" />
</form>
</body>
</html>

測試目錄:json

 

提交後顯示json格式OK:表示上傳完成springboot

相關文章
相關標籤/搜索