基于FastDFS在SpringBoot上的上传与下载
方法:
1.在application.properties里设置参数,其中tracker-list是tracker的端口
fdfs.so-timeout=1500 fdfs.connect-timeout=600 fdfs.tracker-list=192.168.118.12:22122
2.导包,使用Maven进行导包依赖
<!-- FastDFS --> <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.26.6</version> </dependency>
3.编写上传页面
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>pageurl:fileUploadPage</title> </head> <body> <div align="center"> <h1>上传文件</h1> <form action="solveUpload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <button type="submit">提交</button> </form> </div> </body> </html>
4.注入FastFileStorageClient对象
@Autowired
FastFileStorageClient fc;
5.编写上传和下载方法
上传:
@RequestMapping("solveUpload") @ResponseBody public String solveUpload(@RequestParam("file")MultipartFile file) throws IOException { Set<MetaData> metaDataSet=new HashSet<>();//设置metaDataSet文件头元数据 metaDataSet.add(new MetaData("Author", "littlepage")); metaDataSet.add(new MetaData("CreateDate","2019-7-24")); StorePath uploadFile=fc.uploadFile(file.getInputStream(),file.getSize(), file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1), metaDataSet);//上传直接返回数据,这边简略了关于路径保存数据库,直接返回路径 return uploadFile.getPath(); }
下载:
@RequestMapping("apic") @ResponseBody public ResponseEntity<byte[]> down(HttpServletResponse resp){ HttpHeaders httpHeaders=new HttpHeaders();//new出一个httpHeader对象 httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);//设置Media类型为直接下载类型 httpHeaders.setContentDispositionFormData("name", "aa.png");//设置名字和文件名 byte[] bs=fc.downloadFile("group1", "M00/00/00/wKh2DF03SZiAQvM4AADNi5XjeDQ722.png",
new DownloadByteArray());//下载 return new ResponseEntity<>(bs,httpHeaders,HttpStatus.OK);//返回封装实体 }