package com.bgxt.wechat.utils;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.Properties;import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import com.bgxt.wechat.common.HttpRequest;
import com.bgxt.wechat.config.FastDfsProperties;import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;/**
* @author
*2019年1月14日下午4:00:54
* fastdfs工具类,上传下载删除;
*/
public class FastDFSUtils implements Serializable {private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(FastDFSUtils.class);
// 组名
private static String currentGroup = "group1";
// 端口号
private static String currentPort = "23000";
/**
* 2019年1月11日下午2:44:43
* store_path当前有2个
* currentstorePath表示store_path后面的下标(从0开始)
*/
private static String currentstorePath = "1";/**
* is: 文件流
* fileName: 文件名字
*/
public static String uploadPic(InputStream is, String fileName) {
String path = null;
// ClientGloble 读配置文件
ClassPathResource resource = new ClassPathResource("fdfs_client.conf");
try {
InputStream stream = resource.getInputStream();
InputStreamReader in = new InputStreamReader(stream, "utf-8");
Properties proper = new Properties();
try (BufferedReader reader = new BufferedReader(in)) {
String line;
while ((line = reader.readLine()) != null) {
String[] strArr = line.split("=");
if(line!=null && strArr.length>0){
String key = strArr[0];
String value = strArr[1];
if(key.contains("fastdfs.")){
proper.setProperty(key.trim(), value.trim());
}
}
}
}
ClientGlobal.initByProperties(proper);
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
if (trackerServer == null) {
throw new IllegalStateException("getConnection return null --------------------->>");
}
StorageServer storageServer = trackerClient.getStoreStorage(trackerServer, currentGroup);
String storageIp = storageServer.getSocket().getInetAddress().getHostAddress();
storageServer = new StorageServer(storageIp, Integer.parseInt(currentPort),
Integer.parseInt(currentstorePath));StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
// 读取流
byte[] content = new byte[is.available()];
is.read(content, 0, content.length);// 图片11.jpg 根据图片名称得到图片后缀 jpg
String ext = FilenameUtils.getExtension(fileName);
// mata list是表文件的描述
NameValuePair[] meta_list = new NameValuePair[2];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", ext);// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
path = storageClient1.upload_file1(content, ext, meta_list);} catch (Exception e) {
log.error("上传图片到fastDFS失败={}", e.getMessage());
e.printStackTrace();
}
return path;
}// 第一种删除方式,根据组名和文件路径 wzg
public static Integer Delete(String group, String storagePath) {
int i = -1;
// ClientGloble 读配置文件
ClassPathResource resource = new ClassPathResource("fdfs_client.conf");try {
ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;StorageClient storageClient = new StorageClient(trackerServer, storageServer);
// int i = storageClient.delete_file("group1",
// "M00/00/00/wKgRcFV_08OAK_KCAAAA5fm_sy874.conf");
i = storageClient.delete_file(group, storagePath);
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);} catch (Exception e) {
e.printStackTrace();
}
return i;
}// 第二种删除方式,直接根据整体路径删除 wzg
public static Integer Delete1(String storagePath) {
int i = -1;
// ClientGloble 读配置文件
ClassPathResource resource = new ClassPathResource("fdfs_client.conf");try {
ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
if (trackerServer == null) {
throw new IllegalStateException("getConnection return null --------------------->>");
}
StorageServer storageServer = trackerClient.getStoreStorage(trackerServer, currentGroup);
String storageIp = storageServer.getSocket().getInetAddress().getHostAddress();
storageServer = new StorageServer(storageIp, Integer.parseInt(currentPort),
Integer.parseInt(currentstorePath));
if (storageServer == null) {
throw new IllegalStateException("getStoreStorage return null=====>");
}
StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
// int i = storageClient.delete_file("group1",
// "M00/00/00/wKgRcFV_08OAK_KCAAAA5fm_sy874.conf");
i = storageClient1.delete_file1(storagePath);
System.out.println(i == 0 ? "删除成功=====>" : "删除失败:" + i);} catch (Exception e) {
e.printStackTrace();
}
return i;
}// 下载
public static int download_file(String group_name, String remote_filename, File file) {
int result = -1;
ClassPathResource resource = new ClassPathResource("fdfs_client.conf");try {
//ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());
InputStream stream = resource.getInputStream();
InputStreamReader in = new InputStreamReader(stream, "utf-8");
Properties proper = new Properties();
try (BufferedReader reader = new BufferedReader(in)) {
String line;
while ((line = reader.readLine()) != null) {
String[] strArr = line.split("=");
if(line!=null && strArr.length>0){
String key = strArr[0];
String value = strArr[1];
if(key.contains("fastdfs.")){
proper.setProperty(key.trim(), value.trim());
}
}
}
}
ClientGlobal.initByProperties(proper);
System.out.println("==========>>>>>>>"+resource.getClassLoader().getResource("fdfs_client.conf").getPath());
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
if (trackerServer == null) {
throw new IllegalStateException("getConnection return null --------------------->>");
}
StorageServer storageServer = trackerClient.getStoreStorage(trackerServer, currentGroup);
String storageIp = storageServer.getSocket().getInetAddress().getHostAddress();
storageServer = new StorageServer(storageIp, Integer.parseInt(currentPort),
Integer.parseInt(currentstorePath));
if (storageServer == null) {
throw new IllegalStateException("getStoreStorage return null=====>");
}StorageClient storageClient = new StorageClient(trackerServer, storageServer);
byte[] b = storageClient.download_file(group_name, remote_filename);
IOUtils.write(b, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//通过流的方式把微信发送过来的url文件直接上传fastdfs服务器上
public static String downloadUploadImg(String wxImgUrl) {
InputStream is = null;
File tempFile = null;
String url = null;
try {
tempFile = FastDFSUtils.downloadFromUrl(wxImgUrl);
String[] strs = wxImgUrl.split("/");
System.out.println(strs);
String filename = strs[strs.length - 2] + ".jpeg";
is = new FileInputStream(tempFile);
url = FastDFSUtils.uploadPic(is, filename);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
try {
throw new IOException("文件流关闭失败");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}}
log.info("上传完之后新图片地址=" + (FastDfsProperties.getFileServerPath() +"/"+ url));
return FastDfsProperties.getFileServerPath() +"/"+ url;
}
//通过流的方式把微信发送过来的视频直接上传fastdfs服务器上
public static String downloadUploadVideo(WxMpXmlMessage wxMessage, WxMpService weixinService) {
InputStream is = null;
String url = null;
try {
File file = weixinService.getMaterialService().mediaDownload(wxMessage.getMediaId());
String filename = file.getName();
is = new FileInputStream(file);
url = FastDFSUtils.uploadPic(is, filename);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
try {
throw new IOException("文件流关闭失败");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}}
log.info("上传完之后新图片地址=" + (FastDfsProperties.getFileServerPath() +"/"+ url));
return FastDfsProperties.getFileServerPath() +"/"+ url;
}
//通过流的方式把微信发送过来的视频直接上传fastdfs服务器上
public static String downloadUploadVoice(WxMpXmlMessage wxMessage, WxMpService weixinService) {
InputStream is = null;
String url = null;
String file2=null;
try {
File file1 = weixinService.getMaterialService().mediaDownload(wxMessage.getMediaId());
if (WxConsts.XmlMsgType.VOICE.equals(wxMessage.getMsgType())) {
file2=file1.toString().split(".amr")[0]+".mp3";
}
FastDFSUtils.amrToMp3(file1, new File(file2));
is = new FileInputStream(file2);
url = FastDFSUtils.uploadPic(is, file2);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
try {
throw new IOException("文件流关闭失败");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}}
log.info("上传完之后新图片地址=" + (FastDfsProperties.getFileServerPath() +"/"+ url));
return FastDfsProperties.getFileServerPath() +"/"+ url;
}
public static File downloadFromUrl(String wxImgUrl) {
InputStream is = null;
File file = null;
try {
is = (InputStream) HttpRequest.sendGet(wxImgUrl, "");file = getTemplateFile(is);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
public static File downloadFromUrl1(String wxImgUrl) {
InputStream is = null;
File file = null;
try {
is = (InputStream) HttpRequest.sendGet(wxImgUrl, "");file = getTemplateFile1(is);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
/**
* 获取模板文件--获取到的文件为临时文件,用完后需要手动删除
*
* @param inputStream
* @return 模板文件
* @throws Exception
* 异常抛出
*/
public static File getTemplateFile(InputStream inputStream) throws Exception {
File file = File.createTempFile("temp_image", null);
inputStreamToFile(inputStream, file);
if (file.exists() && file.length() <= 0) {
throw new Exception("临时文件为空");
}
return file;
}
public static File getTemplateFile1(InputStream inputStream) throws Exception {
File file = File.createTempFile("temp_image", ".png");
inputStreamToFile(inputStream, file);
if (file.exists() && file.length() <= 0) {
throw new Exception("临时文件为空");
}
return file;
}
/**
* InputStream 转file
*
* @param ins
* 输入流
* @param file
* 目标文件
*/
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
try {
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
} finally {
if (os != null) {
os.close();
}
if (ins != null) {
ins.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* amr语音格式转MP3
*
* @param amr
* @param mp3
*/
public static void amrToMp3(File amr, File mp3) {
AudioAttributes audio = new AudioAttributes();
Encoder encoder = new Encoder();
// audio.setCodec("pcm_s16le");
audio.setCodec("libmp3lame");
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
try {
encoder.encode(amr, mp3, attrs);
} catch (IllegalArgumentException e) {
} catch (InputFormatException e) {
} catch (EncoderException e) {
}
}}
package com.bgxt.wechat.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;/**
*@author:
*creattime:2019年1月14日下午4:07:59
*/
@Component
@Configuration
public class FastDfsProperties {
private static String fileServerPath;
public static String getFileServerPath() {
return fileServerPath;
}
@Value("${fastdfs.fileServerPath}")
public void setFileServerPath(String fileServerPath) {
FastDfsProperties.fileServerPath = fileServerPath;
}
}
fastdfs:
fileServerPath: 192.168.10.149 #文件服务器地址
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>