赞
踩
说明:Spring Boot应用中如何实现文件上传功能
<?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.zslaa</groupId> <artifactId>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>
<!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>
package com.zslaa.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; /** * 控制器 */ @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 "上传成功"; } }
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); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。