方式1:
使用fastDFSClient上传
//获取前端传过来的数据 是由type和url组成
JSonArray imglists = param.getJSonArray("imgurlq");
for (Integer i = 0; i < imglists.size(); i++) {
JSonObject jsonObject = (JSONObject) imglists.get(i);
String type = jsonObject.getString("type");
String url = jsonObject.getString("url");
String[] split = url.split(",");
if (imgfile.length() == 0) {
imgfile = fastDFSClient.uploadFile(split[1], "jpg"); //上传蹄片
}
@Component
public class FastDFSClient {
private final static Logger LOGGER = LoggerFactory.getLogger(FastDFSClient.class);
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private FdfsWebServer fdfsWebServer;
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(),
file.getSize(),
FilenameUtils.getExtension(file.getOriginalFilename()),
null);
return getResAccessUrl(storePath);
}
public String uploadFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
StorePath storePath = storageClient.uploadFile(inputStream,
file.length(),
FilenameUtils.getExtension(file.getName()),
null);
return getResAccessUrl(storePath);
}
public String uploadFile(byte[] bytes,long fileSize,String extension) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
StorePath storePath = storageClient.uploadFile(byteArrayInputStream,
fileSize,extension,null);
return getResAccessUrl(storePath);
}
public String uploadFile(String content,String extension) {
byte[] buff = base64Util.base64ToAdjust(content);
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath storePath = storageClient.uploadFile(stream,buff.length,extension,null);
return getResAccessUrl(storePath);
}
public List uploadBatchFile(String contents,String exts) {
List rets = new ArrayList<>();
List contentl = Stream.of(contents.split(",")).collect(Collectors.toList());
List extl = Stream.of(exts.split(",")).collect(Collectors.toList());
if (contentl.size() != extl.size()) {
return null;
}
for (int i = 0;i < contentl.size();i++) {
rets.add(uploadFile(contentl.get(i),extl.get(i)));
}
return rets;
}
private String getResAccessUrl(StorePath storePath) {
//String fileUrl = fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath();
return storePath.getFullPath();
}
public byte[] download(String fileUrl) {
String group = fileUrl.substring(0,fileUrl.indexOf("/"));
String path = fileUrl.substring(fileUrl.indexOf("/")+1);
byte[] bytes = storageClient.downloadFile(group,path,new DownloadByteArray());
return bytes;
}
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(),
storePath.getPath());
}catch (FdfsUnsupportStorePathException e) {
LOGGER.warn(e.getMessage());
}
}
}
其他的配置
pom文件中引入
com.github.tobato fastdfs-client1.27.2 ch.qos.logback logback-classic
application.yml
# FastDFS
fdfs:
so-timeout: 1501
connect-timeout: 601
thumb-image:
width: 150
height: 150
web-server-url: ***.***.***.***:**** #图片上传 本地服务器地址
tracker-list: ***.***.***.***:****
方式二:
使用minio上传
public void mulUpload() throws Exception {
ParamMap map = getParamMap();
String picArray = map.get("picArray"); //post方式获取前端参数
JSonArray jsonArray = JSONArray.parseArray(picArray);
List list = JSONObject.parseArray(jsonArray.toJSonString(), PicDto.class);
String path = PathKit.getWebRootPath()+"/upload"; //本地upload路径
List nameList = Lists.newArrayList();
if(list == null || list.size() ==0){
return;
}
for(PicDto pic:list){
File file = FileUtils.convertbase64ToFile(pic.getUrl(),path,pic.getName()); //图片的base64代码生成文件
FileProp fileProp = resourceService.uploadFile(file,file.getName()); //上传文件到服务器
String newName=fileProp.getCurrentName();
nameList.add(newName);
}
renderJson(nameList);//返回上传到服务器上的文件名称list
}
辅助文件
public class FileUtils {
public static File convertbase64ToFile(String filebase64String, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
base64Decoder decoder = new base64Decoder();
byte[] bfile = decoder.decodeBuffer(filebase64String);
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
pom文件
io.minio minio7.1.2
config.properties
minioEndpoint=http:/
FileProp uploadFile(File file, String fileName) throws Exception;
InputStream downloadFile(String path) throws Exception;
boolean deleteFile(String path) throws IOException;
public String getUrl(String key);
default String validateFile(File file, String ext) {
if (Objects.isNull(file)) {
throw new RuntimeException("上传文件为空");
}
String fileName = CommonUtils.getUUID() + ext;
//判断是否可以上传
if (!canUpload(ext)) {
file.delete();
throw new RuntimeException("非法的文件类型");
}
return fileName;
}
default boolean canUpload(String ext){
if (acceptExt.contains(ext)||acceptPicExt.contains(ext)) {
return true;
}
return false;
}
default String getExt(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}
}
public class MinioOSS implements ResourceService {
private static Logger logger = Logger.getLogger(MinioOSS.class);
private static String ENDPOINT = PropKit.get("minioEndpoint");
// private static String ACCESSKEYID = PropKit.get("minioAccessKeyId");
// private static String ACCESSKEYSECRET = PropKit.get("minioAccessKeySecret");
private static String ACCESSKEYID = "minioadmin";
private static String ACCESSKEYSECRET = "minioadmin";
private static String BUCKETNAME = PropKit.get("minioBucketName");
private static String BUCKETNAMEPIC = PropKit.get("minioBucketNamePic");
private static MinioClient minioClient = MinioClient.builder()
.endpoint(ENDPOINT)
.credentials(ACCESSKEYID, ACCESSKEYSECRET)
.build();
static {
try {
boolean isExist =
minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKETNAME).build());
if (!isExist) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKETNAME).build());
minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(BUCKETNAME).config("{n" +
" "Statement": [n" + "{n" + ""Action": [n" + ""s3:GetBucketLocation",n" + ""s3:ListBucket"n" +
" ],n" + ""Effect": "Allow",n" + ""Principal": "*",n" + ""Resource": "arn:aws:s3:::ttms"n" +
" },n" + "{n" + ""Action": "s3:GetObject",n" + ""Effect": "Allow",n" + ""Principal": "*",n" +
""Resource": "arn:aws:s3:::ttms
@Override
public String getUrl(String key) {
String ext = getExt(key);
String url = null;
try {
if (acceptPicExt.contains(ext)) {
url = minioClient.getObjectUrl(BUCKETNAMEPIC, key);
} else {
url = minioClient.getObjectUrl(BUCKETNAME, key);
}
if (StrKit.notBlank(url)) {
url = url.replace(ENDPOINT,"");
// if (url.contains(".mp4")) {
// url= url.replace(".mp4", "b.action");
// }
}
logger.info("资源路径:"+url);
return url;
} catch (Exception e) {
e.printStackTrace();
logger.error("获取资源的url路径失败:" + e.getMessage());
return "";
}
}
public static String getPICENDPOINT() {
return bashPath + "/" + BUCKETNAMEPIC + "/";
}
public static String getFILEENDPOINT() {
return bashPath + "/" + BUCKETNAME + "/";
}
}



