JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<%@ include file="/WEB-INF/views/include/head.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form role="form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input id="file" type="file" class="file" name="file">
<button type="submit" class="btn btn-default col-sm-2 col-sm-offset-4">提交</button>
</form>
<script>
$("#file").fileinput({
uploadAsync:false, //默认异步上传
showUpload: false, //是否显示上传按钮,跟随文本框的那个
showRemove : true, //显示移除按钮,跟随文本框的那个
showCaption: true,//是否显示标题,就是那个文本框
showPreview : true, //是否显示预览,不写默认为true
dropZoneEnabled: false,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
maxFileCount: 1, //表示允许同时上传的最大文件个数
enctype: 'multipart/form-data',
validateInitialCount:true,
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
allowedFileTypes: ['image'],//配置允许文件上传的类型
allowedPreviewTypes : [ 'image'],//配置所有的被预览文件类型
allowedPreviewMimeTypes : [ 'jpg', 'png', 'gif' ],//控制被预览的所有mime类型
language : 'zh'
})
</script>
</body>
</html>
后台
/**
* DFS
*
* @author MaxHo
*
*/
@Controller
public class Demo {
// private static ResourceLoader resourceLoader = new
// DefaultResourceLoader();
// @Value("${FILE_SERVER_URL}")
// private String FILE_SERVER_URL;
@RequestMapping(value = "Demo")
public String demo() {
return "Demo";
}
@RequestMapping(value = "uploadFile", method = RequestMethod.POST)
@ResponseBody
public void uploadFile(@RequestParam(value = "file") MultipartFile uploadFile) throws Exception {
// @param fileBuffer 文件内容
byte[] fileBuffer = uploadFile.getBytes();
// @param prefix 文件后缀名,例如 "txt","jpg"等
String prefix = StringUtils.substringAfterLast(uploadFile.getOriginalFilename(), ".");
// @param metaList K-V形式的属性列表,K ,V都是String类型
List<NameValuePair> metaList = new ArrayList<NameValuePair>();
NameValuePair nvp = new NameValuePair("fileAuthor", "YY");
metaList.add(nvp);
// FastDfs的文件操作类
String upload = FdfsUtils.upload(fileBuffer, prefix, metaList);
System.out.println(upload);
FdfsUtils.download(upload, "D:\\test.jpg");
//----------------------------------------------------------------------------
// String confPath =
// resourceLoader.getResource("conf/common/fdfs_client.properties").getFile().getAbsolutePath();
// ClientGlobal.init(confPath);
// TrackerClient trackerClient = new TrackerClient();
// TrackerServer trackerServer = trackerClient.getConnection();
// StorageServer storageServer = null;
// StorageClient storageClient = new StorageClient(trackerServer,
// storageServer);
// //上传图片
// String[] upload_file =
// storageClient.upload_file(uploadFile.getBytes(), prefix, null);
// //返回的结果上传图片的url
// String fUrl = this.FILE_SERVER_URL + "/" + upload_file[0] + "/" + upload_file[1];
// System.out.println(fUrl);
}
}
utils
/**
* FastDfs的文件操作类
* 实现文件的上传和下载等功能
*/
public class FdfsUtils {
private static Logger logger = LoggerFactory.getLogger(FdfsUtils.class);
private static ResourceLoader resourceLoader = new DefaultResourceLoader();
private static final String GROUP_NAME_SEP = "--";
//客户端配置文件初始化
static {
try {
String confPath = resourceLoader.getResource("conf/common/fdfs_client.properties").getFile().getAbsolutePath();
ClientGlobal.init(confPath);
} catch (Exception e) {
logger.error("加载FastDFS配置文件失败",e);
}
}
/**
* @throws IOException
* 上传单个文件到fastDFS
* @param fileBuffer 文件内容
* @param prefix 文件后缀名,例如 "txt","jpg"等
* @param metaList K-V形式的属性列表,K ,V都是String类型
* @return 文件名称
* @throws
*/
public static String upload(byte[] fileBuffer,String prefix,List<NameValuePair> metaList) {
TrackerServer server = null;
try{
server = getTrackerServer();
StorageClient client = getStorageClient(server);
String[] results = client.upload_file(fileBuffer, prefix, metaList.toArray(new NameValuePair[metaList.size()]));
return results[0] + GROUP_NAME_SEP + results[1];
}catch(Exception e){
logger.error("上传文件失败",e);
}finally{
if(server!=null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 上传单个文件到fastDFS
* @param filePath 本地文件路径
* @param prefix 文件后缀名,例如 "txt","jpg"等
* @param metaList K-V形式的属性列表,K ,V都是String类型
* @return 文件名称
* @throws
*/
public static String upload(String filePath,String prefix,List<NameValuePair> metaList){
TrackerServer server = null;
try{
server = getTrackerServer();
StorageClient client = getStorageClient(server);
String[] results = client.upload_file(filePath, prefix,metaList.toArray(new NameValuePair[metaList.size()]));
return results[0] + GROUP_NAME_SEP + results[1];
}catch(Exception e){
logger.error("上传文件失败",e);
}finally{
if(server!=null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 追加文件内容fastDFS,适用于大文件多次上传
* @param fileBuffer 要追加的文件内容
* @param remoteFileName 要追加的文件名称
* @return 0 成功 ,其他 失败
* @throws
*/
public static int append(byte[] fileBuffer,String remoteFileName){
TrackerServer server = null;
try{
server = getTrackerServer();
StorageClient client = getStorageClient(server);
String[] names = remoteFileName.split(GROUP_NAME_SEP);
String group_name = names[0];
String appender_filename = names[1];
int result = client.append_file(group_name, appender_filename, fileBuffer);
return result;
}catch(Exception e){
logger.error("追加上传文件失败",e);
}finally{
if(server!=null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return -1;
}
/**
* 下载整个文件
* @param fileName 文件名称
* @return 文件内容
* @throws
*/
public static byte[] download(String remoteFileName){
TrackerServer server = null;
try{
server = getTrackerServer();
StorageClient client = getStorageClient(server);
String[] names = remoteFileName.split(GROUP_NAME_SEP);
String group_name = names[0];
String remote_filename = names[1];
return client.download_file(group_name, remote_filename);
}catch(Exception e){
logger.error("下载文件失败",e);
}finally{
if(server!=null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 下载文件到本地文件中
* @param remoteFileName 远程文件名称
* @param localFileName 本地文件名称(全路径)
* @return 0 成功 其他:失败
* @throws
*/
public static int download(String remoteFileName,String localFileName){
TrackerServer server = null;
try{
server = getTrackerServer();
StorageClient client = getStorageClient(server);
String[] names = remoteFileName.split(GROUP_NAME_SEP);
String group_name = names[0];
String remote_filename = names[1];
return client.download_file(group_name, remote_filename, localFileName);
}catch(Exception e){
logger.error("下载文件失败",e);
}finally{
if(server!=null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return -1;
}
/**
* 删除fastDFS中的指定文件
* @param remoteFileName 远程文件名称
* @return 0 成功 其他:失败
* @throws
*/
public static int delete(String remoteFileName){
TrackerServer server = null;
try{
server = getTrackerServer();
StorageClient client = getStorageClient(server);
String[] names = remoteFileName.split(GROUP_NAME_SEP);
String group_name = names[0];
String remote_filename = names[1];
return client.delete_file(group_name, remote_filename);
}catch(Exception e){
logger.error("删除文件失败",e);
}finally{
if(server!=null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return -1;
}
private static TrackerServer getTrackerServer() throws IOException{
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
return trackerServer;
}
private static StorageClient getStorageClient(TrackerServer server){
StorageServer storageServer = null;
StorageClient client = new StorageClient(server, null);
return client;
}
}
fdfs_client.properties
connect_timeout = 2
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = FastDFS1234567890
tracker_server = 192.168.1.187:22122