玖叶教程网

前端编程开发入门

实现Spring Boot 文件上传功能,有它就够了

  本篇内容主要是对实现Spring Boot 文件上传功能做一个小小的总结,希望可以帮到你。 

  在java中, 文件上传使用较早和较广泛的方式是使用Apache Commons FileUpload,这是Apache组织提供的一个文件上传的库, 但是在Servlet 3.0 之后, Java官方就提供了文件上传的实现。

  Spring Boot本身并没有文件上传的实现, 但是其封装了一个上层的接口,可以兼容多种文件上传的实现库,也就是说,可以选择并切换不同的文件上传实现, 但是Spring Boot的代码是维持不变的。

  该内容以 Commons FileUpload作为文件上传的实现库,前端使用最原始的JSP页面演示在Spring Boot中实现文件上传功能。

  示例相关环境及版本如下:

  Spring Boot: 2.2.5.RELEASE

  Commons Fileupload: 1.3.2

  示例开发步骤:

  1.在pom.xml 中添加 Commons FileUpload依赖

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3.2</version>

</dependency>

2.新增文件上传的控制器类FileUploadController,在该控制器中添加访问文件上传路径的地址映射。

@Controller

public class FileUploadController {

@GetMapping("/upload_page")

public String uploadPage() {

return "upload_page";

}

}

  以上请求配置通过http://localhost:8080/upload_page 访问位于WEB-INF\views 目录下的

  upload_page.jsp文件。

  3.在WEB-INF\views 目录下新增upload_page.jsp文件。

<!-- upload_page.jsp Author:Chen Xueming -->

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Upload File Page</title>

</head>

<body>

文件上传

<form action="do_upload" method="post" enctype="multipart/form-data">

<input type="file" name="myfile"> <br>

<input type="submit" value="上传">

</form>

</body>

</html>

  4.在FileUploadController 控制器中添加处理上传文件的映射。

@ResponseBody

@PostMapping("/do_upload")

public Map<String, String> doUpload(@RequestParam(name = "myfile") MultipartFile file) {

Map<String, String> rtn = new HashMap<String, String>();

String sTargetClassPath = null;

try {

// 1. 获取或创建文件上传目录 , 这里放置再项目构建后的目录 target的子目录upload下面

sTargetClassPath = ResourceUtils.getURL("classpath:").getPath(); // xxxx/target/classes/

File rootFolder = new File(sTargetClassPath);

File uploadFolder = new File(rootFolder.getAbsolutePath(), "../upload/");

if (!uploadFolder.exists()) {

uploadFolder.mkdirs();

}

String fullFileName = file.getOriginalFilename();

String fileName = StringUtils.cleanPath(fullFileName);

String targetFullFilePath = uploadFolder.getAbsolutePath() + "/" + fileName;

File targetFile = new File(targetFullFilePath);

if (targetFile.exists()) {

targetFile.createNewFile();

}

InputStream in = file.getInputStream();

FileOutputStream out = new FileOutputStream(targetFile);

int n = 0;

byte[] b = new byte[1024];

while ((n = in.read(b)) != -1) {

out.write(b, 0, n);

}

out.close();

in.close();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

rtn.put("success", "true");

return rtn;

}

  以上使用的是Java的基本IO包实现文件的保存,也可以使用无阻塞的nio包,编码上相对更简洁。

上传的文件保存在编译后的目录target的子目录中。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言