spring boot搭建文件服務(wù)器解決同時(shí)上傳多個(gè)圖片和下載的問(wèn)題
在平時(shí)的業(yè)務(wù)場(chǎng)景中,避免不了,要搭建文件上傳服務(wù)器,作為公共服務(wù)。一般情況,只做了單個(gè)文件的上傳,實(shí)際業(yè)務(wù)場(chǎng)景中,卻發(fā)現(xiàn)單個(gè)文件上傳,并不能滿足一些業(yè)務(wù)需求,因此我們需要解決如何寫一個(gè)同時(shí)上傳多個(gè)文件的接口,并返回可下載的文件地址;
廢話不多講,不再?gòu)念^建立一個(gè) Spring boot 項(xiàng)目,如果不知道的話,請(qǐng)直接前往官網(wǎng)查看實(shí)例。
下面我們以上傳圖片為例,示例相對(duì)簡(jiǎn)單,僅供參考:
1 后端上傳圖片接口邏輯
UploadController.java package com.zz.controllers.fileUpload; import com.zz.Application; import com.zz.model.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.net.Inet4Address; import java.net.InetAddress; import java.nio.file.Path; import java.util.ArrayList; import java.util.UUID; import static com.zz.config.ConfigConstants.getFileDir; @RestController @Configuration public class UploadController { private static final Logger log = LoggerFactory.getLogger(Application.class); @Value("${server.port}") private String port; //獲取當(dāng)前IP地址 public String getIp() { InetAddress localhost = null; try { localhost = Inet4Address.getLocalHost(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } return localhost.getHostAddress(); } @PostMapping(value = "/upload", consumes = {"multipart/form-data"}) public Response upload(@RequestParam("file") MultipartFile[] files, Response response) { log.info("上傳多個(gè)文件"); StringBuilder builder = new StringBuilder(); // file address String fileAddress ="http://"+ getIp()+ ":" + port + File.separator; ArrayList<String> imgUrls = new ArrayList<String>(); try { for (int i = 0; i < files.length; i++) { // old file name String fileName = files[i].getOriginalFilename(); // new filename String generateFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf(".")); // store filename String distFileAddress = fileAddress + generateFileName; builder.append(distFileAddress+","); imgUrls.add(distFileAddress); // generate file to disk files[i].transferTo(new File(getFileDir() + generateFileName)); } } catch (Exception e) { e.printStackTrace(); } response.setMsg("success"); log.info(builder.toString()); response.setData(imgUrls); return response; } }
相對(duì)于單個(gè)文件的接收,我們這里直接接受多個(gè) file 對(duì)象,然后遍歷生成每個(gè)對(duì)應(yīng)的地址。
其中:
getFileDir 設(shè)置存放圖片的地址,我選擇存在項(xiàng)目外的其他地方
com.zz.config.ConfigConstants.getFileDir package com.zz.config; public class ConfigConstants { public static String fileDir; public static String getFileDir() { fileDir = "/Users/wz/projects/blog/uploadFile/"; return fileDir; } }
當(dāng)我們把文件生成到指定的文件夾后,我們?nèi)绾闻渲迷诋?dāng)前server下訪問(wèn)項(xiàng)目外的靜態(tài)文件圖片資源并可以下載呢?
這個(gè)我們就要利用 spring boot配置文件 application.yml, 當(dāng)前還有其他方法比如 WebMvcConfigurer 這里不再贅述。
application.yml pring: jpa: show-sql: true hibernate: ddl-auto: update servlet: multipart: max-file-size: 10MB max-request-size: 10MB profiles: active: dev # 靜態(tài)資源配置 mvc: static-path-pattern: /** resources: static-locations: file:/Users/wz/projects/blog/uploadFile/,classpath:/static/,classpath:/resources/,classpath:/file/,classpath:/templates/ server: use-forward-headers: true tomcat: remote-ip-header: X-Real-IP protocol-header: X-Forwarded-Proto #自定義 my: tokenURL: "55555" authURL: "88888"
這樣之后我們?cè)谏傻慕Y(jié)果中的 http://192.168.31.77:8080/a7ef32e3922b46aea256a93dd53de288.png ,這樣的地址就可以把文件實(shí)質(zhì)性的指向了 file:/Users/wz/projects/blog/uploadFile/ ,這樣大致就是一個(gè)簡(jiǎn)單文件服務(wù)器的配置了,當(dāng)然遠(yuǎn)不及此,還有壓縮一類的功能,后續(xù)再聊。
后端邏輯已經(jīng)很清晰;
那前端如何向后端同時(shí)發(fā)送多個(gè) file 對(duì)象呢?
2 前端多個(gè)文件上傳如何傳參
html
<input type="file" multiple class="el-upload" accept="image/*" name="file">
js
//upload var uploadBtn = document.querySelector('.el-upload'); uploadBtn.onchange = function (e) { let files = this.files; console.log(this.files); const xhr = new XMLHttpRequest(); xhr.open("post", "/upload", true); // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { console.log(JSON.parse(this.responseText)); const {data} = JSON.parse(this.responseText); if(!data) return; const imageList = data.slice(0); let imageStr = ''; imageList.forEach(img=>{ imageStr += `<img src="${img}" />`; }); document.getElementById("result").innerHTML = imageStr; } }; const formData = new FormData(); // 多個(gè)file 同時(shí)上傳 if(files && files.length){ for (let i=0;i<files.length;i++) { formData.append("file", files[i]) } } console.log(formData); xhr.send(formData); };
前端通過(guò) FormData 傳參數(shù)發(fā)送POST請(qǐng)求;
區(qū)別于之前的單個(gè) formData.append(); 這里我們可以同時(shí) append 多個(gè)相同名字的文件二進(jìn)制文件流;

如圖結(jié)果正常顯示,當(dāng)我們部署到服務(wù)器的時(shí)候,這個(gè)就可以當(dāng)作一個(gè)web服務(wù)器供大家使用。
相關(guān)文章
Java運(yùn)行時(shí)多態(tài)性的實(shí)現(xiàn)
Java運(yùn)行時(shí)多態(tài)性的實(shí)現(xiàn)...2006-12-12關(guān)于ResponseEntity類和HttpEntity及跨平臺(tái)路徑問(wèn)題
這篇文章主要介紹了關(guān)于ResponseEntity類和HttpEntity及跨平臺(tái)路徑問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07easycode配置成mybatis-plus模板的實(shí)現(xiàn)方法
本文主要介紹了easycode配置成mybatis-plus模板的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09Spring?Feign超時(shí)設(shè)置深入了解
Spring?Cloud中Feign客戶端是默認(rèn)開(kāi)啟支持Ribbon的,最重要的兩個(gè)超時(shí)就是連接超時(shí)ConnectTimeout和讀超時(shí)ReadTimeout,在默認(rèn)情況下,也就是沒(méi)有任何配置下,F(xiàn)eign的超時(shí)時(shí)間會(huì)被Ribbon覆蓋,兩個(gè)超時(shí)時(shí)間都是1秒2023-03-03MyBatis獲取插入記錄的自增長(zhǎng)字段值(ID)
本文分步驟給大家介紹了MyBatis獲取插入記錄的自增長(zhǎng)字段值的方法,在文中給大家提到了mybatis返回插入數(shù)據(jù)的自增長(zhǎng)id,需要的朋友可以參考下2017-11-11Java打印斐波那契前N項(xiàng)的實(shí)現(xiàn)示例
這篇文章主要介紹了Java打印斐波那契前N項(xiàng)的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02