引入openfeign
<springcloud.openfeign.version>2.1.1.RELEASE</springcloud.openfeign.version>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>${springcloud.openfeign.version}</version>
</dependency>
文件上传微服务:
@RestController
@RequestMapping("/file")
public class UploadController {
@Autowired
private FastDfsService fastDfsService;
/**
* 单文件上传
* @param file
* @return
*/
@PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public JsonResult uploadFile(@RequestPart("file") MultipartFile file) {
System.out.print("文件上传服务中:"+file.getOriginalFilename());
Map<String, String> map = null;
try {
map = fastDfsService.uploadFile(file);
} catch (IOException e) {
new JsonResult<>(e);
}
return new JsonResult(map, "文件上传成功");
}
/**
* 多文件上传
* @param
* @return
*/
@PostMapping(value = "/uploadFiles",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public JsonResult uploadFiles(@RequestPart("files") MultipartFile[] files) {
List<Object> data = new ArrayList<>();
for (MultipartFile file:files){
Map<String, String> map = null;
try {
map = fastDfsService.uploadFile(file);
data.add(map);
} catch (IOException e) {
new JsonResult<>(e);
}
}
return new JsonResult(data, "文件上传成功");
}
@PostMapping(value = "/deleteFile")
public Map<String,Object> deleteFile(@RequestParam("fileUrl") String fileUrl){
int t = fastDfsService.deleteFile(fileUrl);
Map<String,Object> message = new HashMap<>();
if(t==1){
message.put("code",1);
message.put("msg","删除文件成功");
return message;
}
message.put("code",0);
message.put("msg","删除文件失败");
return message;
}
}
调用服务:
@FeignClient(value = "vcsrm-upload", configuration = UpLoadFeignClient.MultipartSupportConfig.class)
public interface UpLoadFeignClient {
@PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public JsonResult uploadFile(@RequestPart("file") MultipartFile file);
@PostMapping(value = "/file/uploadFiles",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public JsonResult uploadFiles(@RequestPart("files") MultipartFile[] files);
@PostMapping(value = "/file/deleteFile")
public Map<String,Object> deleteFile(@RequestParam("fileUrl") String fileUrl);
@Configuration
class MultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
}
UploadFileServiceImpl.java
@Service
public class UploadFileServiceImpl implements UploadFileService {
@Autowired
private UpLoadFeignClient upLoadFeignClient;
@Override
public JsonResult uploadFile(MultipartFile file) {
return upLoadFeignClient.uploadFile(file);
}
@Override
public JsonResult uploadFiles(MultipartFile[] files) {
return upLoadFeignClient.uploadFiles(files);
}
@Override
public Map<String, Object> deleteFile(String fileUrl) {
return upLoadFeignClient.deleteFile(fileUrl);
}
}
配置fdfs文件服务器:
<fastDFS.client.version>1.26.1-RELEASE</fastDFS.client.version>
<!--FastDFS客户端-->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>${fastDFS.client.version}</version>
</dependency>
application.yml或application.properties
server:
port: 8082
spring:
application:
name: file-upload
servlet:
multipart:
max-file-size: 10MB #限制文件大小
eureka:
client:
service-url:
defaultZone: http://xx:xx@127.0.0.1:10086/eureka
instance:
ip-address: 127.0.0.1
prefer-ip-address: true
fdfs:
soTimeout: 1500 #socket连接超时时长
connectTimeout: 600 #连接tracker服务器超时时长
resHost: 61.157.96.xx
storagePort: 22100
thumbImage: #缩略图生成参数,可选
width: 150
height: 150
trackerList: #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port
- 61.157.96.82:22122
FastDFSConfig.java
@Component
@Data
public class FastDFSConfig {
@Value("${fdfs.resHost}")
private String resHost;
@Value("${fdfs.storagePort}")
private String storagePort;
}
FastDFSClientImporter.java
@Configuration
@Import(FdfsClientConfig.class)
解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastDFSClientImporter {
@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory factory = new MultipartConfigFactory();
// 一个文件最大KB,MB
factory.setMaxFileSize(DataSize.ofMegabytes(10));
// 设置总上传数据总大小
factory.setMaxRequestSize(DataSize.ofMegabytes(20));
// 设置文件大小限制 ,超出设置页面会抛出异常信息,
// 这样在文件上传的地方就需要进行异常信息的处理了;
//factory.setMaxFileSize("128MB"); // KB,MB
/// 设置总上传数据总大小
//factory.setMaxRequestSize("256MB");
//设置文件路径
//factory.setLocation("/excel_src");
return factory.createMultipartConfig();
}
}
FastDfsService.java
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.proto.storage.DownloadFileWriter;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xx.upload.config.FastDFSConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* @data ${DATA}
*/
@Slf4j
@Component
public class FastDfsService {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private FastDFSConfig fastDFSConfig; // 项目参数配置
@Autowired
private ThumbImageConfig thumbImageConfig;
/**
* 上传一个文件
*/
public Map<String, String> uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
return getResult(storePath);
}
/**
* 将一段字符串生成一个文件上传
*/
public Map<String, String> uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(Charset.forName("UTF-8"));
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
return getResult(storePath);
}
/**
* 上传一张图片, 服务器生成2张图片, 一张原图, 一张缩略图
*/
public Map<String, String> uploadImg(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadImageAndCrtThumbImage(
file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
String smallImgPath = thumbImageConfig.getThumbImagePath(storePath.getPath());
Map<String, String> resultMap = getResult(storePath);
resultMap.put("smallImgPath", smallImgPath);
return resultMap;
}
// 封装上传的 返回结果
private Map<String, String> getResult(StorePath storePath) {
Map<String, String> resultMap = new HashMap<String, String>();
String fileUrl = "http://" + fastDFSConfig.getResHost() + ":" + fastDFSConfig.getStoragePort() + "/" + storePath.getFullPath();
resultMap.put("fileUrl", fileUrl);
resultMap.put("fullPath", storePath.getFullPath());
resultMap.put("path", storePath.getPath());
resultMap.put("group", storePath.getGroup());
return resultMap;
}
/**
* 下载文件
*/
public String downloadFile(String group, String path, String filePath) {
String downloadFile = storageClient.downloadFile(group, path, new DownloadFileWriter(filePath));
return downloadFile;
}
/**
* 下载文件
*/
public byte[] downloadFile(String group, String path) {
byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
return bytes;
}
/**
* 删除文件
*/
public int deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return 0;
}
try {
StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
log.warn(e.getMessage());
return 0;
}
return 1;
}
/**
* 删除文件
*/
public int deleteFile(String group, String path) {
if (StringUtils.isEmpty(group) || StringUtils.isEmpty(path)) {
return 0;
}
try {
storageClient.deleteFile(group, path);
} catch (Exception e) {
log.warn(e.getMessage());
return 0;
}
return 1;
}
}