fdfs_client.conf 配置文件
connect_timeout=30
network_timeout=60
#存储日志文件的基本路径
base_path=/wx/fastdfs/client
#tracker_server可以多次触发,tracker_server格式是"主机:端口",主机可以是主机名或ip地址
tracker_server=*.*.*.*:22122
log_level=info
#如果使用连接池默认值为false
use_connection_pool = false
# 空闲时间超过此时间的连接将被关闭,默认值是3600
connection_pool_max_idle_time = 3600
# 如果从跟踪服务器加载FastDFS参数,默认值是false
load_fdfs_parameters_from_tracker=false
use_storage_id = false
storage_ids_filename = storage_ids.conf
#端口号必须和nginx里面配置的端口号一致,否则访问不了图片
http.tracker_server_port=80
# token 防盗链功能,开启后每次访问需要一个token
http_anti_steal_token=true
# 密钥-自己设置
http_secret_key=FastDFS1234567890
FastDFSUtils.java
package com.thinkgem.jeesite.utils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import org.apache.commons.io.FilenameUtils;
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 it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
/**
* @author wzg
*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 {
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));
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;
}
public static String uploadPic(byte[] pic ,String name,long size){
String path = null;
// 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));
StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
//图片11.jpg 根据图片名称得到图片后缀 jpg
String ext = FilenameUtils.getExtension(name);
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName",name);
meta_list[1] = new NameValuePair("fileExt",ext);
meta_list[2] = new NameValuePair("fileSize",String.valueOf(size));
// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
path = storageClient1.upload_file1(pic, ext, meta_list);
} catch (Exception e) {
// TODO Auto-generated catch block
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, BufferedOutputStream output) {
int result = -1;
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=====>");
}
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
byte[] b = storageClient.download_file(group_name, remote_filename);
try {
if (b != null) {
System.out.println("文件下载成功=====>");
output.write(b);
result = 0;
}
} catch (Exception e) {// 用户可能取消了下载
e.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} 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]+".wav";
}
amrToMp3(file1, new File(file2));
is = new FileInputStream(file1);
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;
}*/
/**
* 获取模板文件--获取到的文件为临时文件,用完后需要手动删除
*
* @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;
}
/**
* 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("wav");
attrs.setAudioAttributes(audio);
try {
encoder.encode(amr, mp3, attrs);
} catch (IllegalArgumentException e) {
} catch (InputFormatException e) {
} catch (EncoderException e) {
}
}
}