Spring Boot文件上传

本文讲解Spring Boot应用中如何实现文件上传功能。

1 创建项目,导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yiidian</groupId>
    <artifactId>ch02_06_springboot_fileupload</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 导入springboot父工程. 注意:任何的SpringBoot工程都必须有的!!! -->
    <!-- 父工程的作用:锁定起步的依赖的版本号,并没有真正到依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.11.RELEASE</version>
    </parent>

    <dependencies>
        <!--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>
    </dependencies>
</project>

2 设计上传页面

内容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>一点教程网-文件上传页面</title>
</head>
<body>
文件上传页面

<hr/>
<form action="/uploadAttach" method="post" enctype="multipart/form-data">
	请选择文件:<input type="file" name="attach"/><br/>
	<input type="submit" value="开始上传"/>
</form>
</body>
</html>

3 编写Controller处理文件

package com.yiidian.controller;

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

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

/**
 * 控制器
 * 一点教程网 - www.yiidian.com
 */
@RestController
public class UploadController {
	/*
	 * 接收文件
	 */
	@RequestMapping("/uploadAttach")
	public String upload(@RequestParam("attach")MultipartFile file) throws Exception{
		//处理文件
		System.out.println("文件原名称:"+file.getOriginalFilename());
		System.out.println("文件类型:"+file.getContentType());
		
		//保存到硬盘
		file.transferTo(new File("c:/"+file.getOriginalFilename()));

		return "上传成功";
	} 
}

4 编写引导类

package com.yiidian;

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

/**
 * Spring Boot引导类
 * 一点教程网 - www.yiidian.com
 */
@SpringBootApplication
public class MyBootApplication {

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

}

5 运行测试

结果为:

 

源码下载:https://pan.baidu.com/s/1RlNUFwlX6ovzowyJTMwWQQ

热门文章

优秀文章