基于SpringBoot實(shí)現(xiàn)上傳2種方法工程代碼實(shí)例
創(chuàng)建SpringBoot工程:
再導(dǎo)入所需要的依賴(lài):
<dependency> <groupId>net.oschina.zcx7878</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.27.0.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency>
創(chuàng)建上傳業(yè)務(wù)層程序:
package cn.dzz.fastdfs.service; import org.apache.commons.lang3.StringUtils; import org.csource.fastdfs.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; import java.util.Map; /** * @author DaiZhiZhou * @file Boot-With-FastDFS * @create 2020-08-13 8:55 */ // @PropertySource() @Component public class UploadService { @Value("${fastdfs.tracker_servers}") private String tracker_servers; @Value("${fastdfs.connect_timeout_in_seconds}") private int connect_timeout; @Value("${fastdfs.network_timeout_in_seconds}") private int network_timeout; @Value("${fastdfs.charset}") private String charset; public Map<String,Object> upload(MultipartFile multipartFile) { if (multipartFile == null) { throw new RuntimeException("文件不能為空"); } // 上傳至fastDFS, 返回文件id String fileId = this.fdfsUpload(multipartFile); if (StringUtils.isEmpty(fileId)) { System.out.println("上傳失敗"); throw new RuntimeException("上傳失敗"); } Map<String, Object> map=new HashMap<>(); map.put("code",200); map.put("msg","上傳成功"); map.put("fileId",fileId); return map; } /** * 上傳至fastDFS * @param multipartFile * @return 文件id */ private String fdfsUpload(MultipartFile multipartFile) { // 1. 初始化fastDFS的環(huán)境 initFdfsConfig(); // 2. 獲取trackerClient服務(wù) TrackerClient trackerClient = new TrackerClient(); try { TrackerServer trackerServer = trackerClient.getConnection(); // 3. 獲取storage服務(wù) StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer); // 4. 獲取storageClient StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage); // 5. 上傳文件 (文件字節(jié), 文件擴(kuò)展名, ) // 5.1 獲取文件擴(kuò)展名 String originalFilename = multipartFile.getOriginalFilename(); String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); // 5.2 上傳 String fileId = storageClient1.upload_file1(multipartFile.getBytes(), extName, null); return fileId; } catch (Exception e) { System.out.println(e); return null; } } /** * 初始化fastDFS的環(huán)境 */ private void initFdfsConfig() { try { ClientGlobal.initByTrackers(tracker_servers); ClientGlobal.setG_connect_timeout(connect_timeout); ClientGlobal.setG_network_timeout(network_timeout); ClientGlobal.setG_charset(charset); } catch (Exception e) { System.out.println(e); } } }
創(chuàng)建上傳控制器:
package cn.dzz.fastdfs.controller; import cn.dzz.fastdfs.service.UploadService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import java.util.Map; /** * @author DaiZhiZhou * @file Boot-With-FastDFS * @create 2020-08-13 8:58 */ @RestController @RequestMapping("upload") public class UploadController { @Autowired private UploadService uploadService; /** * 作上傳 */ @RequestMapping("doUpload") public Map<String,Object> doUpload(MultipartFile mf){ System.out.println(mf.getOriginalFilename()); Map<String, Object> map = uploadService.upload(mf); return map; } }
在static目錄中創(chuàng)建index.html用于上傳測(cè)試:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>文件上傳</h1> <hr> <form action="/upload/doUpload" method="post" enctype="multipart/form-data"> <input type="file" name="mf"> <input type="submit" value="上傳"> </form> </body> </html>
運(yùn)行SpringBoot進(jìn)行測(cè)試:
測(cè)試成功:
查看文件位置也可以被訪(fǎng)問(wèn)到:
上傳文件實(shí)現(xiàn)方式二:
更改依賴(lài):
<!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client --> <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.26.7</version> </dependency>
創(chuàng)建一個(gè)配置類(lèi)UploadProperties
package cn.dzz.fastdfs.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; /** * @author DaiZhiZhou * @file Boot-With-FastDFS * @create 2020-08-13 9:10 */ @Data @Component @ConfigurationProperties(prefix = "upload") public class UploadProperties { private String baseUrl; private List<String> allowTypes; }
更改之前的yml配置:
fdfs: so-timeout: 2500 # 讀取時(shí)間 connect-timeout: 600 # 連接超時(shí)時(shí)間 thumb-image: # 縮略圖 width: 100 height: 100 tracker-list: # tracker服務(wù)配置地址列表 - 服務(wù)器或者虛擬機(jī)IP:22122 upload: base-url: http://服務(wù)器或者虛擬機(jī)IP/ allow-types: - image/jpeg - image/png - image/bmp - image/gif
編寫(xiě)UploadProperties.java
package cn.dzz.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; /** * @author DaiZhiZhou * @file fdfs * @create 2020-08-13 9:33 */ @ConfigurationProperties(prefix = "upload") @Data public class UploadProperties { private String baseUrl; private List<String> allowTypes; }
業(yè)務(wù)層:
package cn.dzz.service; import cn.dzz.config.UploadProperties; import com.github.tobato.fastdfs.domain.fdfs.StorePath; import com.github.tobato.fastdfs.service.FastFileStorageClient; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; /** * @author DaiZhiZhou * @file fdfs * @create 2020-08-13 9:34 */ @Component @EnableConfigurationProperties(UploadProperties.class) public class UploadService { private Log log= LogFactory.getLog(UploadService.class); @Autowired private FastFileStorageClient storageClient; @Autowired private UploadProperties prop; public String uploadImage(MultipartFile file) { // 1、校驗(yàn)文件類(lèi)型 String contentType = file.getContentType(); if (!prop.getAllowTypes().contains(contentType)) { throw new RuntimeException("文件類(lèi)型不支持"); } // 2、校驗(yàn)文件內(nèi)容 try { BufferedImage image = ImageIO.read(file.getInputStream()); if (image == null || image.getWidth() == 0 || image.getHeight() == 0) { throw new RuntimeException("上傳文件有問(wèn)題"); } } catch (IOException e) { log.error("校驗(yàn)文件內(nèi)容失敗....{}", e); throw new RuntimeException("校驗(yàn)文件內(nèi)容失敗"+e.getMessage()); } try { // 3、上傳到FastDFS // 3.1、獲取擴(kuò)展名 String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), "."); // 3.2、上傳 StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null); // 返回路徑 return prop.getBaseUrl() + storePath.getFullPath(); } catch (IOException e) { log.error("【文件上傳】上傳文件失敗!....{}", e); throw new RuntimeException("【文件上傳】上傳文件失敗!"+e.getMessage()); } } }
控制器:
package cn.dzz.controller; import cn.dzz.service.UploadService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; import java.util.Map; /** * @author DaiZhiZhou * @file fdfs * @create 2020-08-13 9:35 */ @RequestMapping("upload") @RestController public class UploadController { @Autowired private UploadService uploadService; @RequestMapping("doUpload") public Map<String,Object> doUpload(MultipartFile multipartFile) { System.out.println(multipartFile.getOriginalFilename()); Map<String, Object> map = new HashMap<>(); String filePath = uploadService.uploadImage(multipartFile); map.put("filePath", filePath); return map; } }
還是一樣的上傳頁(yè)面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>文件上傳</h1> <hr> <form action="/upload/doUpload" method="post" enctype="multipart/form-data"> <input type="file" name="mf"> <input type="submit" value="上傳"> </form> </body> </html>
運(yùn)行發(fā)現(xiàn)空指針異常,檢查發(fā)現(xiàn)表單名稱(chēng)沒(méi)對(duì)上,SpringMVC就無(wú)法轉(zhuǎn)換了
<input type="file" name="multipartFile">
再次測(cè)試:
訪(fǎng)問(wèn):
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot 中大文件(分片上傳)斷點(diǎn)續(xù)傳與極速秒傳功能的實(shí)現(xiàn)
- springboot docker jenkins 自動(dòng)化部署并上傳鏡像的步驟詳解
- Spring boot集成Go-FastDFS實(shí)現(xiàn)圖片上傳刪除等功能實(shí)現(xiàn)
- vue+springboot圖片上傳和顯示的示例代碼
- spring boot上傳文件出錯(cuò)問(wèn)題如何解決
- springboot實(shí)現(xiàn)文件上傳步驟解析
- spring boot如何實(shí)現(xiàn)切割分片上傳
- springboot以FTP方式上傳文件到遠(yuǎn)程服務(wù)器
相關(guān)文章
使用spring工廠(chǎng)讀取property配置文件示例代碼
這篇文章主要介紹了使用spring工廠(chǎng)讀取property配置文件示例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01Hibernate悲觀(guān)鎖和樂(lè)觀(guān)鎖實(shí)例詳解
這篇文章主要介紹了Hibernate悲觀(guān)鎖和樂(lè)觀(guān)鎖實(shí)例詳解,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02淺談Java的兩種多線(xiàn)程實(shí)現(xiàn)方式
本篇文章主要介紹了淺談Java的兩種多線(xiàn)程實(shí)現(xiàn)方式,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08Java之Spring認(rèn)證使用Profile配置運(yùn)行環(huán)境講解
這篇文章主要介紹了Java之Spring認(rèn)證使用Profile配置運(yùn)行環(huán)境講解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07Java實(shí)現(xiàn)通過(guò)時(shí)間獲取8位驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了Java如何通過(guò)時(shí)間獲取8位驗(yàn)證碼(每?jī)蓚€(gè)小時(shí)生成一個(gè)),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11MyBatis Plus復(fù)合主鍵問(wèn)題的解決
在數(shù)據(jù)庫(kù)設(shè)計(jì)中,有時(shí)候需要使用復(fù)合主鍵來(lái)唯一標(biāo)識(shí)表中的一行數(shù)據(jù),本文將為您詳細(xì)介紹MyBatis Plus中復(fù)合主鍵的問(wèn)題以及解決方案,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09Java中的FutureTask實(shí)現(xiàn)異步任務(wù)代碼實(shí)例
這篇文章主要介紹了Java中的FutureTask實(shí)現(xiàn)異步任務(wù)代碼實(shí)例,普通的線(xiàn)程執(zhí)行是無(wú)法獲取到執(zhí)行結(jié)果的,FutureTask?間接實(shí)現(xiàn)了?Runnable?和?Future?接口,可以得到子線(xiàn)程耗時(shí)操作的執(zhí)行結(jié)果,AsyncTask?異步任務(wù)就是使用了該機(jī)制,需要的朋友可以參考下2024-01-01JDK8接口的默認(rèn)與靜態(tài)方法-接口與抽象類(lèi)的區(qū)別詳解
這篇文章主要介紹了JDK8接口的默認(rèn)與靜態(tài)方法-接口與抽象類(lèi)的區(qū)別詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下2019-06-06