准备

  1. 下载fastdfs-client-java源码

源码地址 密码:s3sw

  1. 修改pom.xml

    第一个plugins是必需要的,是maven用来编译的插件,第二个是maven打源码包的,可以不要。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
  1. fastdfs-client-java 打包

    直接项目右键,run as maven install

    install成功后,fastdfs-client-java就成功的被安装到本地仓库了。

编写工具类:

  • fdfs_client.conf文件复制一份放到自己项目的resource下面;修改里面的tracker.server,其它的都不用动:
  • 在项目的pom.xml中添加依赖
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
  • 首先来实现文件上传,fastdfs-client-java的上传是通过传入一个byte[ ]来完成的,简单看一下源码:
public String[] upload_file(byte[] file_buff, String file_ext_name,
NameValuePair[] meta_list) throws IOException, MyException{
final String group_name = null;
return this.upload_file(group_name, file_buff, 0, file_buff.length, file_ext_name, meta_list);
}

文件属性

package com.wuwii.utils;

import java.io.Serializable;
import java.util.Arrays; /**
* @ClassName FastDFSFile
* @Description FastDFS上传文件业务对象
* @author zhangkai
* @date 2017年7月18日
*/
public class FastDFSFile implements Serializable{ private static final long serialVersionUID = 2637755431406080379L;
/**
* 文件二进制
*/
private byte[] content;
/**
* 文件名称
*/
private String name;
/**
* 文件长度
*/
private Long size; public FastDFSFile(){ }
public FastDFSFile(byte[] content, String name, Long size){
this.content = content;
this.name = name;
this.size = size;
} public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

编写FastDFS工具类

package com.wuwii.utils;

import java.io.Serializable;

import org.apache.commons.io.FilenameUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; /**
* @ClassName FastDFSUtils
* @Description FastDFS工具类
* @author zhangkai
* @date 2017年7月18日
*/
public class FastDFSUtils implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4462272673174266738L;
private static TrackerClient trackerClient;
private static TrackerServer trackerServer;
private static StorageClient1 storageClient1; static {
try {
//clientGloble读配置文件
ClassPathResource resource = new ClassPathResource("fdfs_client.conf");
ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());
//trackerclient
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
//storageclient
storageClient1 = new StorageClient1(trackerServer,null);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* fastDFS文件上传
* @param file 上传的文件 FastDFSFile
* @return String 返回文件的绝对路径
*/
public static String uploadFile(FastDFSFile file){
String path = null;
try {
//文件扩展名
String ext = FilenameUtils.getExtension(file.getName());
//mata list是表文件的描述
NameValuePair[] mata_list = new NameValuePair[3];
mata_list[0] = new NameValuePair("fileName",file.getName());
mata_list[1] = new NameValuePair("fileExt",ext);
mata_list[2] = new NameValuePair("fileSize",String.valueOf(file.getSize()));
path = storageClient1.upload_file1(file.getContent(), ext, mata_list);
} catch (Exception e) {
e.printStackTrace();
}
return path;
} /**
* fastDFS文件下载
* @param groupName 组名
* @param remoteFileName 文件名
* @param specFileName 真实文件名
* @return ResponseEntity<byte[]>
*/
@org.jetbrains.annotations.NotNull
public static ResponseEntity<byte[]> downloadFile(String groupName, String remoteFileName, String specFileName){
byte[] content = null;
HttpHeaders headers = new HttpHeaders();
try {
content = storageClient1.download_file(groupName, remoteFileName);
headers.setContentDispositionFormData("attachment", new String(specFileName.getBytes("UTF-8"),"iso-8859-1"));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
} /**
* 根据fastDFS返回的path得到文件的组名
* @param path fastDFS返回的path
* @return
*/
public static String getGroupFormFilePath(String path){
return path.split("/")[0];
} /**
* 根据fastDFS返回的path得到文件名
* @param path fastDFS返回的path
* @return
*/
@NotNull
public static String getFileNameFormFilePath(String path) {
return path.substring(path.indexOf("/")+1);
}
}

测试Controller

package com.wuwii.controller;

import java.io.IOException;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile; import com.wuwii.utils.FastDFSFile;
import com.wuwii.utils.FastDFSUtils;
import com.wuwii.utils.PropertyUtil; /**
* FastFDS控制器
* @author zhangkai
*
*/
@Controller
@RequestMapping(value = "/fastdfs")
public class FastFDSController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload (MultipartFile file){
try {
FastDFSFile fastDFSFile = new FastDFSFile(file.getBytes(), file.getOriginalFilename(), file.getSize());
String path = FastDFSUtils.uploadFile(fastDFSFile);
return "redirect:"+ PropertyUtil.get("fastFDS_server") + path;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} @RequestMapping(value = "/download")
public ResponseEntity<byte[]> download (String path, String specFileName){
String filename = FastDFSUtils.getFileNameFormFilePath(path);
String group = FastDFSUtils.getGroupFormFilePath(path);
return FastDFSUtils.downloadFile(group, filename, specFileName);
}
}

最后附上读取配置文件的工具类PropertyUtil

package com.wuwii.utils;

import java.io.InputStream;
import java.util.Properties; /**
* @ClassName PropertyUtil
* @Description 读取配置文件的内容(key,value)
* @author zhangkai
* @date 2017年7月18日
*/
public class PropertyUtil {
public static final Properties PROP = new Properties(); /**
* @Method: get
* @Description: 读取配置文件的内容(key,value)
* @param key
* @return String
* @throws
*/
public static String get(String key) {
if (PROP.isEmpty()) {
try {
InputStream in = PropertyUtil.class.getResourceAsStream("/config.properties");
PROP.load(in);
in.close();
} catch (Exception e) {}
}
return PROP.getProperty(key);
}
}

测试

上传!

下载

下载就很简单了,因为直接获得到二进制流了,返回给客户端即可。

下载需要主要的是,要注意从FastDFS返回的文件名是这种随机码,因此我们需要在上传的时候将文件本身的名字存到数据库,再到下载的时候对文件头重新设置名字即可。

fastDFS与java整合文件上传下载的更多相关文章

  1. CentOS下安装配置NFS并通过Java进行文件上传下载

    1:安装NFS (1)安装 yum install nfs-utils rpcbind (2)启动rpcbind服务 systemctl restart rpcbind.service 查看服务状态 ...

  2. java实现文件上传下载

    喜欢的朋友可以关注下,粉丝也缺. 今天发现已经有很久没有给大家分享一篇技术文章了,于是想了一下给大家分享一篇java实现文件上传下载功能的文章,不喜欢的希望大家勿喷. 想必大家都知道文件的上传前端页面 ...

  3. java web 文件上传下载

    文件上传下载案例: 首先是此案例工程的目录结构:

  4. java+大文件上传下载

    文件上传下载,与传统的方式不同,这里能够上传和下载10G以上的文件.而且支持断点续传. 通常情况下,我们在网站上面下载的时候都是单个文件下载,但是在实际的业务场景中,我们经常会遇到客户需要批量下载的场 ...

  5. FasfDFS整合Java实现文件上传下载

    文章目录     一 : 添加配置文件     二 : 加载配置文件         1. 测试加载配置文件         2. 输出配置文件     三:功能实现         1.初始化连接信 ...

  6. FasfDFS整合Java实现文件上传下载功能实例详解

    https://www.jb51.net/article/120675.htm 在上篇文章给大家介绍了FastDFS安装和配置整合Nginx-1.13.3的方法,大家可以点击查看下. 今天使用Java ...

  7. Java web文件上传下载

    [版权申明:本文系作者原创,转载请注明出处] 文章出处:http://blog.csdn.net/sdksdk0/article/details/52048666 作者:朱培 ID:sdksdk0 邮 ...

  8. java 实现文件上传下载以及查看

    项目的目录结构 代码  IOUtils.java package cn.edu.zyt.util; import java.io.IOException; import java.io.InputSt ...

  9. Jsch - java SFTP 文件上传下载

    使用Jsch上传.下载文件,核心步骤是:获取channel,然后使用get/put方法下载.上传文件 核心代码句: session = jSch.getSession(ftpUserName, ftp ...

随机推荐

  1. 5.1、Android Studio用Logcat编写和查看日志

    Android Studio在Android Monitor中包含了一个logcat的tab,可以打印系统事件,比如垃圾回收发生时,实时打印应用消息. 为了显示需要的信息,你可以创建过滤器,更改需要显 ...

  2. 【一天一道LeetCode】#223. Rectangle Area

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Find th ...

  3. 【C++知识点】单例模式的简单实现

    单例模式是最常见,也是使用最广泛的一种设计模式,其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享. 单例模式的实现方法有很多种,本文只给出一个最简单的实现,如下: ...

  4. 【一天一道LeetCode】#226. Invert Binary Tree

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源:http ...

  5. Hessian源码分析--HessianSkeleton

    HessianSkeleton是Hessian的服务端的核心,简单总结来说:HessianSkeleton根据客户端请求的链接,获取到需要执行的接口及实现类,对客户端发送过来的二进制数据进行反序列化, ...

  6. 手把手教你轻松实现listview上拉加载

    上篇讲了如何简单快速的的实现listview下拉刷新,那么本篇将讲解如何简单快速的实现上拉加载更多.其实,如果你已经理解了下拉刷新的实现过程,那么实现上拉加载更多将变得轻松起来,原理完全一致,甚至实现 ...

  7. iOS中 UIMPMediaPickerController播放系统音乐

    布局如下: 引入框架: #import <AVFoundation/AVFoundation.h> #import <MediaPlayer/MediaPlayer.h> 遵循 ...

  8. 求解n皇后

    要求:在国际象棋上摆放n个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行.同一列或同一斜线上,问有多少种摆法 思路:很直观的想法就是在棋盘上一个一个皇后的摆,如果冲突,则摆放在另一个位置,直至 ...

  9. Gradle 1.12翻译——第二十章. 构建环境

    有关其他已翻译的章节请关注Github上的项目:https://github.com/msdx/gradledoc/tree/1.12,或访问:http://gradledoc.qiniudn.com ...

  10. Ionic APP-Web SPA开发进阶(二)Ionic进阶之路由去哪了

    Ionic进阶之路由去哪了 项目需求 在查看药品时,从药品列表中可以通过点击药品列表获取某一药品详情.提交订单时,同样可以查看药品详情.两种情形下,从药品详情返回后,应分别返回至原来的页面.如下图所示 ...