天天看点

SpringBoot实现文件上传 | 带你读《SpringBoot实战教程》之二十八

上一篇:如何发送基于模板的邮件? | 带你读《SpringBoot实战教程》之二十七 下一篇:SpringBoot实现批量文件上传 | 带你读《SpringBoot实战教程》之二十九

本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,

点击查看视频内容

SpringBoot实现文件上传

在工程中添加依赖:

<!-- spring boot web支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

      <!-- thymeleaf模板依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>           

控制上传文件的大小,在全局配置文件application.properties中添加:

multipart.maxFileSize=500Mb
multipart.maxRequestSize=500Mb           

实现上传的页面:

SpringBoot实现文件上传 | 带你读《SpringBoot实战教程》之二十八
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"></meta>
<title>文件上传</title>
</head>
<body>
    <h2>文件上传</h2>
    <hr/>
    <form method = "POST" enctype="multipart/form-data" action="/upload">
    <p>
        文件<input type="file" name="file"/>
    </p>
    <p>
        <input type="submit" value="上传"/>
    </p>
    </form>
</body>
</html>           

UploadController:

@Controller
public class UploadController {

    @RequestMapping("/index")
    public String toUpload(){
        return "upload";
    }


    @RequestMapping(value="/upload",method=RequestMethod.POST)
    @ResponseBody    
    public String uploadFile(MultipartFile file, HttpServletRequest request) {
        try{
             //创建文件在服务器端的存放路径
            String dir=request.getServletContext().getRealPath("/upload");
            File fileDir = new File(dir);
            if(!fileDir.exists())
                fileDir.mkdirs();
            //生成文件在服务器端存放的名字
            String fileSuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName=UUID.randomUUID().toString()+fileSuffix;
            File files = new File(fileDir+"/"+fileName);
            //上传
            file.transferTO(files);

        }catch(Exception e) {
            e.printStackTrace();
            return "上传失败";
        }

        return "上传成功";
    }
}           

在启动类中添加所有需要扫描的包:

@SpringBootApplication(scanBasePackages="com.qianfeng")           

执行结果:

SpringBoot实现文件上传 | 带你读《SpringBoot实战教程》之二十八

选择文件上传

SpringBoot实现文件上传 | 带你读《SpringBoot实战教程》之二十八
SpringBoot实现文件上传 | 带你读《SpringBoot实战教程》之二十八

配套视频