linux禁止客户端上传文件_实战 FastDFS Java 客户端上传文件
生活随笔
收集整理的這篇文章主要介紹了
linux禁止客户端上传文件_实战 FastDFS Java 客户端上传文件
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
FastDFS 服務(wù)端安裝參考文章:分布式文件系統(tǒng)之 FastDFS
安裝 FastDFS Java 客戶端
先從 GitHub 上將項(xiàng)目源碼克隆下來:
$ git clone https://github.com/happyfish100/fastdfs-client-java.git然后不要忘了部署到 Nexus 依賴私服:
$ mvn clean install deploy最后在需要用到的項(xiàng)目中添加 POM 依賴即可:
<!-- FastDFS Begin --> <dependency><groupId>org.csource</groupId><artifactId>fastdfs-client-java</artifactId><version>1.27-SNAPSHOT</version> </dependency> <!-- FastDFS End -->引入依賴以后在 application.yml 中添加 FastDFS 服務(wù)端配置:
fastdfs:base:# 一般為 Nginx 代理地址url: http://{fastdfs_server ip}/ storage:type: fastdfsfastdfs:tracker_server: {tracker_server ip}創(chuàng)建 FastDFS 工具類
定義文件存儲(chǔ)接口
package com.antoniopeng.fastdfs.service.upload;/*** 文件存儲(chǔ)服務(wù)接口*/ public interface StorageService {/*** 上傳文件** @param data 文件的二進(jìn)制內(nèi)容* @param extName 擴(kuò)展名* @return 上傳成功后返回生成的文件 id;失敗返回 null*/public String upload(byte[] data, String extName);/*** 刪除文件** @param fileId 被刪除的文件id* @return 刪除成功后返回 0,失敗后返回錯(cuò)誤代碼*/public int delete(String fileId); }實(shí)現(xiàn)文件存儲(chǔ)接口
package com.antoniopeng.fastdfs.service.upload;import org.csource.common.NameValuePair; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient1; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerGroup; import org.csource.fastdfs.TrackerServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value;import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter;/*** 文件存儲(chǔ)服務(wù)實(shí)現(xiàn)*/ public class FastDFSStorageService implements StorageService, InitializingBean {private static final Logger logger = LoggerFactory.getLogger(FastDFSStorageService.class);private TrackerClient trackerClient;@Value("${storage.fastdfs.tracker_server}")private String trackerServer;@Overridepublic String upload(byte[] data, String extName) {TrackerServer trackerServer = null;StorageServer storageServer = null;StorageClient1 storageClient1 = null;try {NameValuePair[] meta_list = null; // new NameValuePair[0];trackerServer = trackerClient.getConnection();if (trackerServer == null) {logger.error("getConnection return null");}storageServer = trackerClient.getStoreStorage(trackerServer);storageClient1 = new StorageClient1(trackerServer, storageServer);String fileid = storageClient1.upload_file1(data, extName, meta_list);logger.debug("uploaded file <{}>", fileid);return fileid;} catch (Exception ex) {logger.error("Upload fail", ex);return null;} finally {if (storageServer != null) {try {storageServer.close();} catch (IOException e) {e.printStackTrace();}}if (trackerServer != null) {try {trackerServer.close();} catch (IOException e) {e.printStackTrace();}}storageClient1 = null;}}@Overridepublic int delete(String fileId) {TrackerServer trackerServer = null;StorageServer storageServer = null;StorageClient1 storageClient1 = null;int index = fileId.indexOf('/');String groupName = fileId.substring(0, index);try {trackerServer = trackerClient.getConnection();if (trackerServer == null) {logger.error("getConnection return null");}storageServer = trackerClient.getStoreStorage(trackerServer, groupName);storageClient1 = new StorageClient1(trackerServer, storageServer);int result = storageClient1.delete_file1(fileId);return result;} catch (Exception ex) {logger.error("Delete fail", ex);return 1;} finally {if (storageServer != null) {try {storageServer.close();} catch (IOException e) {e.printStackTrace();}}if (trackerServer != null) {try {trackerServer.close();} catch (IOException e) {e.printStackTrace();}}storageClient1 = null;}}@Overridepublic void afterPropertiesSet() throws Exception {File confFile = File.createTempFile("fastdfs", ".conf");PrintWriter confWriter = new PrintWriter(new FileWriter(confFile));confWriter.println("tracker_server=" + trackerServer);confWriter.close();ClientGlobal.init(confFile.getAbsolutePath());confFile.delete();TrackerGroup trackerGroup = ClientGlobal.g_tracker_group;trackerClient = new TrackerClient(trackerGroup);logger.info("Init FastDFS with tracker_server : {}", trackerServer);} }創(chuàng)建文件存儲(chǔ)工廠類
package com.antoniopeng.fastdfs.service.upload;import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.AutowireCapableBeanFactory;import java.util.HashMap; import java.util.Map;/*** 文件存儲(chǔ)服務(wù)工廠類*/ public class StorageFactory implements FactoryBean<StorageService> {@Autowiredprivate AutowireCapableBeanFactory acbf;/*** 存儲(chǔ)服務(wù)的類型,目前僅支持fastdfs*/@Value("${storage.type}")private String type;private Map<String, Class<? extends StorageService>> classMap;public StorageFactory() {classMap = new HashMap<>();classMap.put("fastdfs", FastDFSStorageService.class);}@Overridepublic StorageService getObject() throws Exception {Class<? extends StorageService> clazz = classMap.get(type);if (clazz == null) {throw new RuntimeException("Unsupported storage type [" + type + "], valid are " + classMap.keySet());}StorageService bean = clazz.newInstance();acbf.autowireBean(bean);acbf.initializeBean(bean, bean.getClass().getSimpleName());return bean;}@Overridepublic Class<?> getObjectType() {return StorageService.class;}@Overridepublic boolean isSingleton() {return true;} }配置文件存儲(chǔ)工廠類
package com.antoniopeng.fastdfs.service.upload;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;/*** Java 配置方式定義 StorageFactory 的 Bean 使其可以被依賴注入*/ @Configuration public class FastDFSConfiguration {@Beanpublic StorageFactory storageFactory() {return new StorageFactory();} }創(chuàng)建 FastDFS 訪問控制器
package com.antoniopeng.fastdfs.controller.upload;import com.antoniopeng.fastdfs.service.upload.StorageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile;import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;@CrossOrigin(origins = "*", maxAge = 3600) @RestController public class UploadController {@Value("${fastdfs.base.url}")private String FASTDFS_BASE_URL;@Autowiredprivate StorageService storageService;/*** 文件上傳** @param dropFile Dropzone* @param editorFiles wangEditor* @return*/@RequestMapping(value = "upload", method = RequestMethod.POST)public Map<String, Object> upload(MultipartFile dropFile, MultipartFile[] editorFiles) {Map<String, Object> result = new HashMap<>();// Dropzone 上傳if (dropFile != null) {result.put("fileName", writeFile(dropFile));}// wangEditor 上傳if (editorFiles != null && editorFiles.length > 0) {List<String> fileNames = new ArrayList<>();for (MultipartFile editorFile : editorFiles) {fileNames.add(writeFile(editorFile));}result.put("errno", 0);result.put("data", fileNames);}return result;}/*** 將圖片寫入指定目錄** @param multipartFile* @return 返回文件完整路徑*/private String writeFile(MultipartFile multipartFile) {// 獲取文件后綴String oName = multipartFile.getOriginalFilename();String extName = oName.substring(oName.lastIndexOf(".") + 1);// 文件存放路徑String url = null;try {String uploadUrl = storageService.upload(multipartFile.getBytes(), extName);url = FASTDFS_BASE_URL + uploadUrl;} catch (IOException e) {e.printStackTrace();}// 返回文件完整路徑return url;} }- 文章作者:彭超
- 本文首發(fā)于個(gè)人博客:https://antoniopeng.com
- 版權(quán)聲明:本博客所有文章除特別聲明外,均采用 CC BY-NC-SA 4.0 許可協(xié)議。轉(zhuǎn)載請(qǐng)注明來自 彭超的博客!
總結(jié)
以上是生活随笔為你收集整理的linux禁止客户端上传文件_实战 FastDFS Java 客户端上传文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 直接拖动元器件_电子元器件常规检测和判断
- 下一篇: 节点图一般的比例_基于图的异常检测(二)