1. 程式人生 > >SpringBoot學習6:springboot文件上傳

SpringBoot學習6:springboot文件上傳

web ppi mapping hash http conf itl 請求 except

1、編寫頁面uploadFile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上傳文件</title>
</head>
<body>
<form action="uploadFile" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <
input type="submit" value="上傳"> </form> </body> </html>

2、編寫controller

package com.bjsxt.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
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; /** * Created by Administrator on 2019/2/5. */ @RestController public class UploadFileController { @RequestMapping(value = "/uploadFile",method = RequestMethod.POST) public
Map<String,Object> uploadFile(MultipartFile myfile){ Map<String,Object> returnMap=new HashMap<String,Object>(); try{ myfile.transferTo(new File("e:/"+myfile.getOriginalFilename())); returnMap.put("msg","上傳成功"); }catch (Exception e){ e.printStackTrace(); returnMap.put("msg","上傳失敗"); } return returnMap; } }

3、編寫啟動類

package com.bjsxt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by Administrator on 2019/2/5.
 */
@SpringBootApplication
public class App {

    public static void main(String[] args){
        SpringApplication.run(App.class,args);
    }
}

4、設置上傳文件的大小限制

  需要添加一個springboot的配置文件,名字為application.properties,放在resource文件夾下,添加以下內容

#設置單個文件上傳的最大大小
spring.http.multipart.maxFileSize=200MB
#設置一次請求上傳文件的總容量的大小
spring.http.multipart.maxRequestSize=200MB

5、啟動項目即可,在瀏覽器中訪問http://localhost:8080/uploadFile.html即可

目錄結構

技術分享圖片

  

SpringBoot學習6:springboot文件上傳