1.注入fdfs客户端
import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
@Configuration
@Import(FdfsClientConfig.class)
//解决jmx重复复注册bean问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {
}
application.yml中的配置文件 #文件上传相关的配置 ly: upload: baseUrl: http://image.leyou.com/ allowTypes: - image/jpeg - image/png - image/bmp
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
//和配置文件中的ly。upload绑定 ,这个类中的属性会根据名字进行绑定
@ConfigurationProperties(prefix = "ly.upload")
public class UploadProperties {
private String baseUrl;
private List<String> allowTypes;
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public List<String> getAllowTypes() {
return allowTypes;
}
public void setAllowTypes(List<String> allowTypes) {
this.allowTypes = allowTypes;
}
}
@Service
//使用配置类
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private ThumbImageConfig thumbImageConfig;
private final Logger log = LoggerFactory.getLogger(UploadService.class);
允许类型放配置文件
//private static final List<String> ALLOW_TYPE = Arrays.asList("image/jpeg","image/png","image/bmp");
//注入配置类
@Autowired
private UploadProperties uploadProperties;
public String uploadImage(MultipartFile file) {
try {
//校验文件类型
String contentType = file.getContentType();
if(!uploadProperties.getAllowTypes().contains(contentType)){
throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
}
//校验文件内容
BufferedImage image = ImageIO.read(file.getInputStream());
if (image==null){
throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
}
保存文件
//File dest = new File("D:\\JAVA全套资料\\资料\\FastDFS", file.getOriginalFilename());//保存的路径
//file.transferTo(dest);
//上传到fastdfs
//获取后缀
String extension = StringUtils.substringAfterLast(file.getOriginalFilename(),".");
//上传
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
//返回路径
//这里路径可以放在配置文件里
return uploadProperties.getBaseUrl() + storePath.getFullPath();
}catch (IOException e){
log.error("上传文件失败",e);
throw new LyException(ExceptionEnums.BRAND_SAVE_ERROR);
}
}
}