Springboot MultipartFile文件上傳與下載的實(shí)現(xiàn)示例
yml文件配置是否可以上傳及上傳附件大小
servlet: multipart: # 允許文件上傳 enabled: true # 單個(gè)文件大小 max-file-size: 20MB # 設(shè)置總上傳的文件大小 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(); // 要上傳的目標(biāo)文件存放的絕對(duì)路徑 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ù)庫(kù)信息 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); } // 設(shè)置響應(yīng)的頭部信息 response.setHeader("content-disposition", "attachment;filename=" + fileName); // 設(shè)置響應(yīng)內(nèi)容的類型 response.setContentType(FileUtils.fileContentType(fileName) + "; charset=" + charsetCode); // 設(shè)置響應(yīng)內(nèi)容的長(zhǎng)度 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 設(shè)置響應(yīng)頭部信息 * @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("關(guān)閉流{} 異常", e.getMessage(),e); e.printStackTrace(); } } } }
到此這篇關(guān)于Springboot MultipartFile文件上傳與下載的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)Springboot MultipartFile文件上傳與下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring MVC之mvc:resources如何處理靜態(tài)資源
這篇文章主要介紹了Spring MVC之mvc:resources如何處理靜態(tài)資源問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-03-03Java中關(guān)鍵字synchronized的使用方法詳解
synchronized關(guān)鍵字可以作為函數(shù)的修飾符,也可作為函數(shù)內(nèi)的語(yǔ)句,也就是平時(shí)說(shuō)的同步方法和同步語(yǔ)句塊,下面這篇文章主要給大家介紹了關(guān)于Java中synchronized使用的相關(guān)資料,需要的朋友可以參考下2021-08-08Elasticsearch QueryBuilder簡(jiǎn)單查詢實(shí)現(xiàn)解析
這篇文章主要介紹了Elasticsearch QueryBuilder簡(jiǎn)單查詢實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08深入淺析Spring 的aop實(shí)現(xiàn)原理
AOP(Aspect-OrientedProgramming,面向方面編程),可以說(shuō)是OOP(Object-Oriented Programing,面向?qū)ο缶幊蹋┑难a(bǔ)充和完善。本文給大家介紹Spring 的aop實(shí)現(xiàn)原理,感興趣的朋友一起學(xué)習(xí)吧2016-03-03MyBatis中${}?和?#{}?有什么區(qū)別小結(jié)
${}?和?#{}?都是?MyBatis?中用來(lái)替換參數(shù)的,它們都可以將用戶傳遞過來(lái)的參數(shù),替換到?MyBatis?最終生成的?SQL?中,但它們區(qū)別卻是很大的,今天通過本文介紹下MyBatis中${}?和?#{}?有什么區(qū)別,感興趣的朋友跟隨小編一起看看吧2022-11-11