导入的依赖
<!-- 添加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>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
yml配置文件的上传路径
spring:
#上传文件路径
upload-path: F:/file/upload/
前端
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<h2 style="color: red">用于上传文件的表单,请求方式必须是 POST </h2>
<h2>上传单个文件</h2>
<form th:action="@{/upload/one}" method="post" enctype="multipart/form-data">
<input th:type="file" name="file" value="请选择文件">
<input th:type="submit" value="上传"/>
</form>
<h2>上传多个文件</h2>
<form th:action="@{/upload/more}" method="post" enctype="multipart/form-data">
<input th:type="file" name="files" value="选择文件" multiple="multiple">
<input th:type="submit" value="上传">
</form>
</body>
</html>
后端-controller
package com.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@Controller
public class UploadFileController {
@Value("${spring.upload-path}")
private String targetDir;
@GetMapping("/toUpload")
public String toUpload() {
return "upload";
}
/**
* 上传单个文件
* @param file
* @return
*/
@PostMapping("/upload/one")
@ResponseBody
public String uploadSigleFile(@RequestParam("file") MultipartFile file) {
try {
String originalFilename = file.getOriginalFilename();
String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
String filename = UUID.randomUUID().toString().replace("-", "") + ext;
file.transferTo(new File(targetDir+ filename));
} catch (IOException e) {
log.error(e.getMessage(), e);
return "上传失败";
}
return "上传成功";
}
/**
* 上传多个文件
* @param files
* @return
*/
@PostMapping(path="/upload/more", consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
public String uploadManyFile(@RequestPart("files") MultipartFile[] files) {
try {
for (MultipartFile file : files) {
String originalFilename = file.getOriginalFilename();
String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
log.debug("ext =" + ext);
String filename = UUID.randomUUID().toString().replace("-", "") + ext;
file.transferTo(new File(targetDir+ filename));
}
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
return "上传成功";
}
}