網站首頁 編程語言 正文
目錄
- 1.準備工作
- 2.文件上傳代碼
1.準備工作
1、新建一個SpringBoot項目加上web依賴, 所有依賴
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.thymeleafgroupId>
<artifactId>thymeleaf-spring5artifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
2、application.properties
# 上傳文件總的最大值
spring.servlet.multipart.max-request-size=10MB
#spring.servlet.multipart.max-request-size=10KB
# 單個文件的最大值
spring.servlet.multipart.max-file-size=10MB
#spring.servlet.multipart.max-file-size=10KB
# 文件上傳路徑
pro.uploadPath=/uploadFile
#spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/uploadFile/
3、新建文件上傳的靜態文件 index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上傳title>
head>
<body>
<h1>單文件上傳h1>
<form method="post" action="/file/upload" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
form>
<h1>傳統手藝文件上傳h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
form>
<h1>多文件上傳h1>
<form method="post" action="/uploads" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="file" name="file"><br>
<input type="submit" value="提交">
form>
body>
html>
2.文件上傳代碼
package com.pro.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
public class UploadController {
@Value("${pro.uploadPath}")
private String uploadPath;
public final static String UPLOAD_PATH_PREFIX = "src/main/resources/static";
/**
* 獲取文件路徑
* @param request 請求體
* @param fileName 文件名稱
* @return 文件路徑
*/
public String getUploadPath(HttpServletRequest request, String fileName) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + uploadPath + "/" + fileName;
}
@GetMapping("/hello")
public String hello(HttpServletRequest request) {
System.out.println("uploadPath --> " + uploadPath);
System.out.println("上下文2 --> " + request.getServletContext().getRealPath("/file"));
File file = new File(UPLOAD_PATH_PREFIX);
System.out.println("UPLOAD_PATH_PREFIX 路徑: " + file.getAbsoluteFile());
try {
String path = ResourceUtils.getURL("classpath:").getPath();
System.out.println("ResourceUtils.getURL.getPath --> " + path);
System.out.println("當前項目的絕對路徑 --> " + new File("").getAbsolutePath());
System.out.println("upload 絕對路徑 --> " + new File("upload").getAbsolutePath());
System.out.println("/upload 絕對路徑 --> " + new File("/upload").getAbsolutePath());
System.out.println("./upload 絕對路徑 --> " + new File("./upload").getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(new Date());
return format;
}
// 單文件上傳
@RequestMapping("/file/upload")
public Object fileUpload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
Map<String, Object> map = new HashMap();
map.put("msg", "上傳成功");
if (multipartFile.isEmpty()) {
map.put("msg", "空文件");
return map;
}
// 獲取文件名
String fileName = multipartFile.getOriginalFilename();
if ("".equals(fileName)) {
map.put("msg", "文件名不能為空");
return map;
}
System.out.println("上傳文件原始的名字: " + fileName);
// 使用uuid生成新文件名
String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf("."), fileName.length());
System.out.println("保存的文件的新名字: " + newFileName);
// 獲取年月日的日期格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(new Date());
// 生成以日期分割的文件路徑
File readPath = new File(UPLOAD_PATH_PREFIX + uploadPath + File.separator + format);
System.out.println("存放的文件夾: " + readPath);
System.out.println("存放文件的絕對路徑: " + readPath.getAbsolutePath());
// 判斷文件夾是否存在
if (!readPath.isDirectory()) {
// 創建文件夾
readPath.mkdirs();
}
// 文件真實的保存路徑
File file = new File(readPath.getAbsolutePath() + File.separator + newFileName);
try {
multipartFile.transferTo(file);
// 獲取存儲路徑
String filePath = getUploadPath(request, format + "/" + newFileName);
map.put("path", filePath);
} catch (IOException e) {
e.printStackTrace();
map.put("msg", "上傳失敗");
}
return map;
}
// 傳統手藝
@PostMapping("/upload")
public Object upload(@RequestParam("file") MultipartFile multipartFile) {
Map<String, Object> map = new HashMap();
map.put("msg", "上傳成功");
if (multipartFile.isEmpty()) {
return "文件不能為空";
}
String fileName = multipartFile.getOriginalFilename();
if ("".equals(fileName)) {
return "文件名不能為空";
}
System.out.println("文件名: " + fileName);
File readPath = new File(UPLOAD_PATH_PREFIX + uploadPath + File.separator + "temp");
if (!readPath.isDirectory()) {
readPath.mkdirs();
}
System.out.println("保存路徑: " + readPath);
InputStream is = null;
FileOutputStream os = null;
try {
is = multipartFile.getInputStream();
os = new FileOutputStream(new File(readPath, fileName));
int len = 0;
byte[] bytes = new byte[1024];
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
map.put("msg", "上傳失敗");
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
// 多文件上傳
@PostMapping("/uploads")
public String uploads(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
for (MultipartFile file : files) {
if (file.isEmpty()) {
return file.getOriginalFilename() + "上傳失敗";
}
File readPath = new File(UPLOAD_PATH_PREFIX + uploadPath + File.separator + "temps");
System.out.println("多文件上傳的位置: " + readPath);
System.out.println("多文件上傳的絕對路徑: " + readPath.getAbsolutePath());
if (!readPath.isDirectory()) {
readPath.mkdirs();
}
File dest = new File(readPath.getAbsolutePath() + File.separator + file.getOriginalFilename());
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
return file.getOriginalFilename() + "上傳失敗";
}
}
return "上傳成功";
}
}
原文鏈接:https://blog.csdn.net/weixin_44953227/article/details/116003269
相關推薦
- 2022-08-16 C/C++函數的調用約定的使用_C 語言
- 2023-10-11 MyBatis-plus wrapper.and用法 | apply
- 2022-05-12 Kotlin operator方法的重載
- 2022-07-06 ELK收集Nginx日志的項目實戰_nginx
- 2022-12-30 Golang通道channel的源碼分析_Golang
- 2023-03-26 數據結構TypeScript之鏈表實現詳解_其它
- 2022-11-08 PostgreSQL查看帶有綁定變量SQL的通用方法詳解_PostgreSQL
- 2022-12-03 GCC?指令詳解及動態庫、靜態庫的使用方法_其它綜合
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支