SpringBoot 文件上传
程序员文章站
2022-06-03 13:18:33
...
基于idea
目录结构
index.xml:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h2>单一文件上传示例</h2>
<div>
<form method="post" enctype="multipart/form-data" action="/uploads/upload1">
<p>
文件1:<input type="file" name="file" />
<input type="submit" value="上传" />
</p>
</form>
</div>
<hr/>
<h2>批量文件上床示例</h2>
<div>
<form method="post" enctype="multipart/form-data" action="/uploads/upload2">
<p>
文件1:<input type="file" name="fileName" />
</p>
<p>
文件2:<input type="file" name="fileName" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</div>
</body>
</html>
pom.xml:
<?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.bj</groupId>
<artifactId>upload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>upload</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Controller:
package com.bj.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Auther: feifei
* @Date: 2018/9/11 15:20
* @Description:
*/
@Controller
@RequestMapping("/uploads")
public class FileUploadController {
String path = "F:/test" ;
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@GetMapping
public String index(){
return "index";
}
@PostMapping("/upload1")
@ResponseBody
public Map<String,String> upload1(@RequestParam("file") MultipartFile file) throws IOException {
logger.info("[文件类型]-[{}]",file.getContentType());
logger.info("[文件名称]-[{}]",file.getOriginalFilename());
logger.info("[文件大小]-[{}]",file.getSize());
// TODO 将文件写入到指定目录(具体开发中有可能是将文件写入到云存储/或者指定目录通过 Nginx 进行 gzip 压缩和反向代理,
// TODO 此处只是为了演示故将地址写成本地电脑指定目录)
String fileName = file.getOriginalFilename();
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
file.transferTo(dest);
Map<String,String> result = new HashMap<>(16);
result.put("contentType",file.getContentType());
result.put("fileName",file.getOriginalFilename());
result.put("fileSize",file.getSize()+"");
return result;
}
/**
* 实现多文件上传
*
* */
@PostMapping("/upload2")
public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files){
if(files.isEmpty()){
return "false";
}
for(MultipartFile file:files){
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if(file.isEmpty()){
return "false";
}else{
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
}
return "true";
}
@PostMapping("/upload3")
@ResponseBody
public void upload2(String base64) throws IOException {
// TODO BASE64 方式的 格式和名字需要自己控制(如 png 图片编码后前缀就会是 data:image/png;base64,)
final File tempFile = new File("C:\\Users\\admin\\Desktop\\springboot\\timg.jpg");
// TODO 防止有的传了 data:image/png;base64, 有的没传的情况
String [] d = base64.split("base64,");
final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]);
FileCopyUtils.copy(bytes, tempFile);
}
}
上一篇: 可变参数列表实现机制与printf()函数源码分析
下一篇: 码云本地上传文件基础教程