在编写该功能模块的时候,首先你要确保已经完成了FastDFS和Nginx的相关配置下载,没有的话可以看下我写的这篇文章:FastDFS环境安装
(1)编写接口
看你的编码习惯吧,我写了个接口
java">// 文件服务
public interface FileService {/*** 上传文件* @param fileBytes 图片文件转成的字节数组* @param fileName 文件名* @return 上传后的文件访问路径*/String uploadImage(byte[] fileBytes,String fileName);/*** 删除文件* @param filePath 文件路径*/void delete(String filePath);
}
(2)编写接口实现类
java">@DubboService
public class FileServiceImpl implements FileService {@Autowiredprivate FastFileStorageClient fastFileStorageClient;@Value("${fdfs.fileUrl}")private String fileUrl; // Nginx访问FastDFS中文件的路径@Overridepublic String uploadImage(byte[] fileBytes, String fileName) {if (fileBytes.length != 0) {try {// 1.将文件的字节数组转为输入流ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);// 2.获取文件的后缀名String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);// 3.上传文件StorePath storePath = fastFileStorageClient.uploadFile(inputStream, inputStream.available(), fileSuffix, null);// 4.返回图片路径String imageUrl = fileUrl + "/"+storePath.getFullPath();return imageUrl;}catch (Exception e){throw new BusException(CodeEnum.UPLOAD_FILE_ERROR);}} else {throw new BusException(CodeEnum.UPLOAD_FILE_ERROR);}}@Overridepublic void delete(String filePath) {fastFileStorageClient.deleteFile(filePath);}
}
(3)编写控制器
java">/*** 文件*/
@RestController
@RequestMapping("/file")
public class FileController {@DubboReferenceprivate FileService fileService;/*** 上传文件* @param file 文件* @return 文件路径* @throws IOException*/@PostMapping("/uploadImage")public BaseResult<String> upload(MultipartFile file) throws IOException {// MultipartFile对象不能再服务间传递,必须转为byte数组byte[] bytes = file.getBytes();String url = fileService.uploadImage(bytes, file.getOriginalFilename());return BaseResult.ok(url);}/*** 删除文件* @param filePath 文件路径* @return 操作结果*/@DeleteMapping("/delete")public BaseResult delete(String filePath){fileService.delete(filePath);return BaseResult.ok();}
}