springBoot整合fastdfs 上传下载
目录结构pom<dependency><groupId>com.github.tobato</groupId><artifactId>fastdfs-client</artifactId><version>1.26.7</version></dependency>ymlserver:port:.
·
- 目录结构
pom
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.7</version>
</dependency>
yml
server:
port: 8081
fdfs:
so-timeout: 2500 # 读取时间
connect-timeout: 600 # 连接超时时间
thumb-image: # 缩略图
width: 100
height: 100
tracker-list: # tracker服务配置地址列表
- 192.168.161.131:22122
upload:
base-url: http://192.168.161.131/
allow-types:
- image/jpeg
- image/png
- image/bmp
- image/gif
- application/msword
entity
@ConfigurationProperties(prefix = "upload")
@Data
@Component
public class UploadProperties {
private String baseUrl;
private List<String> allowTypes;
}
util
@Component
@Slf4j
public class UploadUtil {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private UploadProperties prop;
public String uploadImage(MultipartFile file) {
// 1、校验文件类型
String contentType = file.getContentType();
if (!prop.getAllowTypes().contains(contentType)) {
throw new RuntimeException("文件类型不支持");
}
// 2、校验文件内容
try {
if (file == null ) {
throw new RuntimeException("上传文件有问题");
}
} catch (Exception e) {
log.error("上传文件有问题....{}", e);
throw new RuntimeException("上传文件有问题" + e.getMessage());
}
try {
// 3、上传到FastDFS
// 3.1、获取扩展名
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());
}
}
/**
* 文件下载
*
* @param fileId 文件id
* @param response
* @param downName 文件下载后保存的名字
* @return
* @throws IOException
*/
public void downloadFile(String fileId, HttpServletResponse response, String downName) throws IOException {
//获取group
String group = fileId.substring(0, fileId.indexOf("/"));
//获取路径
String path = fileId.substring(fileId.indexOf("/") + 1);
DownloadByteArray downloadByteArray = new DownloadByteArray();
byte[] bytes = storageClient.downloadFile(group, path, downloadByteArray);
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(downName, "UTF-8"));
response.setCharacterEncoding("UTF-8");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
controller
@RestController
@RequestMapping("upload")
public class UploadController {
@Autowired
private UploadUtil uploadUtil;
@RequestMapping("doUpload")
public Map<String, Object> doUpload(MultipartFile mf) {
//文件名和返回的url保存到数据库 下载的时候通过url找到对应的文件名
System.out.println(mf.getOriginalFilename());
Map<String, Object> map = new HashMap<>();
String url = uploadUtil.uploadImage(mf);
map.put("url", url);
return map;
}
@RequestMapping("/download")
public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException {
fileUrl = "group1/M00/00/00/wKihg1_Our6ANj1rAADoABeizWQ229.doc";
uploadUtil.downloadFile(fileUrl,response,"11.doc");
// 这里只是为了整合fastdfs,所以写死了文件格式。需要在上传的时候保存文件名。下载的时候使用对应的格式
}
}
index.html
<!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>
码云地址:https://gitee.com/zhu_can_admin/elaticsearch.git
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)