springBoot(6)---文件上传

第1步、编写上传页面uploadFile.html

上传页面一般放在src/main/resources/下的static目录下,即静态资源放在static目录下springBoot才能访问

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

第2步、编写UploadController接收上传文件

package com.wzy.controller;

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;

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

@RestController
public class UploadController {
    Map<String,Object> result=new HashMap<String,Object>();
    /**
     * 接收文件
     * */
    @RequestMapping("upload")
    public Map<String,Object> toUpload(@RequestParam("attach")MultipartFile file) throws IOException {
        //处理文件
        System.out.println("文件原名称:"+file.getOriginalFilename());
        System.out.println("文件类型:"+file.getContentType());
        //将文件保存到硬盘
        file.transferTo(new File("e:/"+file.getOriginalFilename()));
        result.put("success",true);
        return result;
    }
}

第3步、编写启动类

package com.wzy.boot_demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.wzy.controller")
public class BootDemoApplication {

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

}

注:启动类上加@ComponentScan扫描包com.wzy.controller

第5步、测试

浏览器输入:http://localhost:8080/uploadFile.html

选择文件后,点击开始上传.根据<form>表单中的action=“upload”,会将请求提交到UploadController中的@RequestMapping中的。

upload映射。

 

当上传的文件超过10M时,会出现org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException异常

即springBoot上传文件限制不超过10M,但是可以修改。

在src/main/resources目录下建立application.properties文件,文件内容如下:

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

spring.servlet.multipart.max-file-size:修改单个文件的大小限制

spring.servlet.multipart.maxRequestSize:修改一个请求(包括多个文件)的大小限制

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值