fastDFS与Java整合上传下载
由于项目需要整合个文件管理,选择使用的是fastDFS。
整合使用还是很方便的。
准备
- 下载
fastdfs-client-java
源码
源码地址 密码:s3sw
- 修改
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>
- 将
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整合上传下载的更多相关文章
- 2013第38周日Java文件上传下载收集思考
2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...
- Java Sftp上传下载文件
需要使用jar包 jsch-0.1.50.jar sftp上传下载实现类 package com.bstek.transit.sftp; import java.io.File; import ja ...
- Java.ftp上传下载
1:jar的maven的引用: 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- java FTP 上传下载删除文件
在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...
- java文件上传下载组件
需求: 支持大文件批量上传(20G)和下载,同时需要保证上传期间用户电脑不出现卡死等体验: 内网百兆网络上传速度为12MB/S 服务器内存占用低 支持文件夹上传,文件夹中的文件数量达到1万个以上,且包 ...
- SSM整合 上传下载之添加商品
上传下载细节: 导入xml配置文件!! Controller中要配置存储路径,调用transferto上传文件 上传图片 要将图片的类设置为 MultipartFile 图片下载: 源码: 页面展示: ...
- java中文上传下载功能实现(自己测试项目)
1.新建maven项目打war包 2.搭建springMVC框架 web.xml文件配置 <?xml version="1.0" encoding="UTF-8&q ...
- JAVA实现上传下载共享文件
1.上传下载共享文件需要用到jcifs,先下载相关JAR包(开源项目的源码,demo,文挡.API应有尽有) https://jcifs.samba.org/src/
- Java文件上传下载原理
文件上传下载原理 在TCP/IP中,最早出现的文件上传机制是FTP.它是将文件由客户端发送到服务器的标准机制. 但是在jsp编程中不能使用FTP方法来上传文件,这是由jsp运行机制所决定的 文件上传原 ...
随机推荐
- Dynamics CRM 开启EmailRouter日志记录
找到mailrouter的安装路径,在service文件夹下找到"Microsoft.Crm.Tools.EmailAgent.xml"这个文件,已管理员方式打开,找到loglev ...
- 详解EBS接口开发之库存事务处理采购接收--补充
除了可以用 详解EBS接口开发之库存事务处理采购接收的方法还可以用一下方法,不同之处在于带有批次和序列控制的时候实现方式不同 The script will load records into ...
- SQL性能优化应该考虑哪些?
1.调整数据结构的设计.这一部分在开发信息系统之前完成,程序员需要考虑是否使用ORACLE数据库的分区功能,对于经常访问的数据库表是否需要建立索引等. 2.调整应用程序结构设计.这一部分也是在开 ...
- Cocos2D将v1.0的tileMap游戏转换到v3.4中一例(二)
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 首先在CatMazeV3中新建CatSprite类,继承于Spr ...
- FreeMarker生成word的代码
用于生成word用的freemarker工具类 package com.ucap.netcheck.utils; import java.io.File; import java.io.File ...
- >/dev/null 2>&1
>/dev/null 2>&1 大部分在 crontab 计划任务中都会年到未尾带 >/dev/null 2>&1,是什么意思呢? > 是重定向 /dev ...
- shell的date
使用方式 : date [-u] [-d datestr] [-s datestr] [--utc] [--universal] [--date=datestr] [--set=datestr] [- ...
- Android View事件机制一些事
本文主要讲述: 自己对View事件机制的一些理解 在项目中遇到的一些坑,解决方案 收集了一些View的事件机制问题 事件的分发原理图 对于一个root viewgroup来说,如果接受了一个点击事件, ...
- (六十三)自定义TabBar和TabBarButtonItem
自定义TabBar 先自定义一个UITabBarController,为了方便跳转与设定属性,借助系统的TabBarController的功能,但是要移除内部的控件然后自己添加一个View和多个按钮. ...
- python 多窗口编辑
同时打开多个文件: 1,vim filename1 filename2 在打开的多个文件中 :next 转到下个文件中 :prev 转到上个文件中 :last/:first 分别到最后一个和第一个文件 ...