SpringBoot: 6.文件上传(转)

 

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即可

目录结构

posted @ 2019-02-24 18:24  咫尺天涯是路人丶  阅读(251)  评论(0编辑  收藏  举报