Springboot MultipartFile文件上傳與下載的實現(xiàn)示例
更新時間:2023年08月16日 15:02:44 作者:掐指一算乀缺錢
在Spring Boot項目中,可以使用MultipartFile類來處理文件上傳和下載操作,本文就詳細介紹了如何使用,具有一定的參考價值,感興趣的可以了解一下
yml文件配置是否可以上傳及上傳附件大小
servlet:
multipart:
# 允許文件上傳
enabled: true
# 單個文件大小
max-file-size: 20MB
# 設置總上傳的文件大小
max-request-size: 50MB/**
* @param files
* @param request
* @Description 上傳文件
* @Throws
* @Return java.util.List
* @Date 2023-08-02 12:11:02
* @Author WangKun
*/
@PostMapping("/upload")
public List<JSONObject> upload(@RequestParam("uploadFiles") MultipartFile[] files, HttpServletRequest request) {
List<JSONObject> list = new ArrayList<>();
for (MultipartFile file : files) { //循環(huán)保存文件
JSONObject result = new JSONObject();
String msg = "";
//判斷上傳文件格式
String fileType = file.getContentType();
// 要上傳的目標文件存放的絕對路徑
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "imags";
//文件名
String fileOldName = file.getOriginalFilename();
if (StringUtils.isNotBlank(fileOldName) && StringUtils.isNotEmpty(fileOldName)
&& StringUtils.isNotBlank(fileType) && StringUtils.isNotEmpty(fileType)
) {
//獲取文件后綴名
String suffixName = fileOldName.substring(fileOldName.lastIndexOf("."));
//重新生成文件名
String fileNewName = UUID.randomUUID() + suffixName;
// 上傳
if (FileUtils.upload(file, path, fileNewName)) {
// 保存數(shù)據(jù)庫信息
String id = addAnnex(fileNewName, fileOldName, path, fileType, file.getSize());
if (StringUtils.isNotBlank(id) && StringUtils.isNotEmpty(id)) {
result.put("fileName", fileNewName);
result.put("id", id);
msg = "文件上傳成功";
}
} else {
msg = "文件上傳失敗";
}
}else{
msg = "文件名或文件類型為空";
}
result.put("msg", msg);
list.add(result);
}
return list;
}文件上傳到了:\target\classes\imags中

下載:
/**
* @param id
* @param response
* @Description 文件下載
* @Throws
* @Return java.util.List<com.alibaba.fastjson2.JSONObject>
* @Date 2023-08-02 13:24:41
* @Author WangKun
*/
@GetMapping("/download")
public void download(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) {
Annex annex = annexService.selectAnnex(id);
String fileName = annex.getFileNewName();
String charsetCode = String.valueOf(StandardCharsets.UTF_8);
try {
File file = new File(annex.getFilePath() + File.separator + fileName);
//中文亂碼解決
String type = request.getHeader("User-Agent").toLowerCase();
// 字符編碼格式
if (type.indexOf("firefox") > 0 || type.indexOf("chrome") > 0) {
//谷歌或火狐
fileName = new String(fileName.getBytes(charsetCode), "iso8859-1");
} else {
//IE
fileName = URLEncoder.encode(fileName, charsetCode);
}
// 設置響應的頭部信息
response.setHeader("content-disposition", "attachment;filename=" + fileName);
// 設置響應內容的類型
response.setContentType(FileUtils.fileContentType(fileName) + "; charset=" + charsetCode);
// 設置響應內容的長度
response.setContentLength((int) file.length());
// 輸出
FileUtils.outStream(Files.newInputStream(file.toPath()), response.getOutputStream());
} catch (Exception e) {
log.error("文件下載異常{}", e.getMessage());
}
}文件工具類:
/**
* @Description 文件上傳工具
* @Author WangKun
* @Date 2023/8/2 10:28
* @Version
*/
@Slf4j
public class FileUtils {
/**
* @param file
* @param path
* @param fileName
* @Description 保存文件
* @Throws
* @Return boolean
* @Date 2023-08-02 12:10:39
* @Author WangKun
*/
public static boolean upload(MultipartFile file, String path, String fileName) {
String realPath = path + "\\" + fileName;
File dest = new File(realPath);
//判斷文件父目錄是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
//保存文件
file.transferTo(dest);
return true;
} catch (IllegalStateException | IOException e) {
log.error("文件上傳{} 異常", e.getMessage(),e);
e.printStackTrace();
return false;
}
}
/**
* @param name
* @Description 設置響應頭部信息
* @Throws
* @Return java.lang.String
* @Date 2023-08-02 13:39:15
* @Author WangKun
*/
public static String fileContentType(String name) {
String result = "";
String fileType = name.toLowerCase();
if (fileType.endsWith(".png")) {
result = "image/png";
} else if (fileType.endsWith(".gif")) {
result = "image/gif";
} else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
result = "image/jpeg";
} else if (fileType.endsWith(".svg")) {
result = "image/svg+xml";
} else if (fileType.endsWith(".doc")) {
result = "application/msword";
} else if (fileType.endsWith(".xls")) {
result = "application/x-excel";
} else if (fileType.endsWith(".zip")) {
result = "application/zip";
} else if (fileType.endsWith(".pdf")) {
result = "application/pdf";
} else if (fileType.endsWith(".mpeg")) { //MP3
result = "audio/mpeg";
} else if (fileType.endsWith(".mp4")) {
result = "video/mp4";
} else if (fileType.endsWith(".plain")) {
result = "text/plain";
} else if (fileType.endsWith(".html")) {
result = "text/html";
} else if (fileType.endsWith(".json")) {
result = "application/json";
} else{
result = "application/octet-stream";
}
return result;
}
/**
* @param is
* @param os
* @Description 文件下載輸出
* @Throws
* @Return void
* @Date 2023-08-02 13:40:47
* @Author WangKun
*/
public static void outStream(InputStream is, OutputStream os) {
try {
byte[] buffer = new byte[10240];
int length = -1;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
os.flush();
}
} catch (Exception e) {
log.error("文件下載{} 異常", e.getMessage(),e);
} finally {
try {
os.close();
is.close();
} catch (IOException e) {
log.error("關閉流{} 異常", e.getMessage(),e);
e.printStackTrace();
}
}
}
}到此這篇關于Springboot MultipartFile文件上傳與下載的實現(xiàn)示例的文章就介紹到這了,更多相關Springboot MultipartFile文件上傳與下載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring MVC之mvc:resources如何處理靜態(tài)資源
這篇文章主要介紹了Spring MVC之mvc:resources如何處理靜態(tài)資源問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03
Elasticsearch QueryBuilder簡單查詢實現(xiàn)解析
這篇文章主要介紹了Elasticsearch QueryBuilder簡單查詢實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08

