SpringBoot整合FastDFS方法过程详解

时间:2021-05-20

一.pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://ponentpublic class FastUtil { private final Logger logger = LoggerFactory.getLogger(FastUtil.class); @Autowired private FastFileStorageClient fastFileStorageClient; /** * 文件上传 * 最后返回fastDFS中的文件名称; * * @param bytes 文件字节 * @param fileSize 文件大小 * @param extension 文件扩展名 * @return fastDfs路径 */ public String uploadFile(byte[] bytes, long fileSize, String extension) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, fileSize, extension, null); return "http://111.111.111.111/"+storePath.getFullPath(); } public byte[] downloadFile(String group,String path) throws IOException { DownloadByteArray downloadByteArray = new DownloadByteArray(); byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray); return bytes; } }

四.配置类 FdfsConfig.java

@Configuration@Import(FdfsClientConfig.class)@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)public class FdfsConfig {}

五.Controller

@RestControllerpublic class FdfsController { @Autowired private FastUtil fastDFSClientWrapper; private final Logger logger = LoggerFactory.getLogger(FdfsController.class); @PostMapping("/upload") @ResponseBody public String upload(MultipartFile file) throws Exception { byte[] bytes = new byte[0]; try { bytes = file.getBytes(); } catch (IOException e) { logger.error("获取文件错误"); e.printStackTrace(); } //获取源文件名称 String originalFileName = file.getOriginalFilename(); //获取文件后缀--.doc String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1); String fileName = file.getName(); //获取文件大小 long fileSize = file.getSize(); System.out.println(originalFileName + "==" + fileName + "==" + fileSize + "==" + extension + "==" + bytes.length); String string = fastDFSClientWrapper.uploadFile(bytes, fileSize, extension); return string; }}

六.前端页面 index.html

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head> <meta charset="UTF-8" /> <title>Insert title here</title></head><body><h1 th:inlines="text">文件上传</h1><form action="upload" method="post" enctype="multipart/form-data"> <p>选择文件: <input type="file" name="file"/></p> <p><input type="submit" value="提交"/></p></form></body></html>

七.开始上传

最后在页面上返回一个URL,可以直接访问

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章