FastDFS操作文件上传,下载,删除

FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理,功能包括:文件存储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合以文件为载体的在线服务,如相册网站、视频网站等等。 -----《百度百科》

最近有在项目里面使用到FastDFS,于是在这里做个记录,以便后续使用查看,至于FastDfs的配置,我会专门出一篇文章进行记录,这里不再赘述。
以下是我写的一个简单的工具类,用于做文件的上传,下载,删除等基础功能。
我们首先需要在SpringBoot项目里面集成FastDFS:

  • 添加Maven依赖
<dependency>
			<groupId>com.github.tobato</groupId>
			<artifactId>fastdfs-client</artifactId>
			<version>1.26.1-RELEASE</version>
			<--! 加入fastdfs的依赖之后会和spring的logback冲突,产生了依赖冲突。
             解决办法:在fastdfs的依赖中排除自身的logback依赖。当然,如果你的项目里面没有集成logback,可能不需要加这个-->
			<exclusions>
				<exclusion>
					<groupId>ch.qos.logback</groupId>
					<artifactId>logback-classic</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

  • 在yml文件里面配置FastDFS的参数
fdfs:
  soTimeout: 1500
  connectTimeout: 600
  thumbImage:             #缩略图生成参数
    width: 150
    height: 150
  trackerList:            #TrackerList参数,支持多个
    - 192.168.x.xxx:22122
  resHost: http://192.168.xxx/
  storagePort: 8888
  • 添加Fast DFS的配置类

@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsClientConf {
}
  • 编写FastDFS工具类
/**
	 * 
	 * @description file upload of type Mutilpart
	 * @author feifei.yuan
	 * @param file: the file will to be uploaded
	 * @return String
	 * @throws IOException
	 * @date Aug 27, 2020 10:30:26 AM
	 */
	public    String upLoadFile(MultipartFile file) {
		StorePath storePath = null;
		try {
			storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
					FilenameUtils.getExtension(file.getOriginalFilename()), null);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return getResAccessUrl(storePath);
	}

	/**
	 * 
	 * @description normal file upload
	 * @author feifei.yuan
	 * @param file : the file to be uploaded
	 * @return String
	 * @throws FileNotFoundException
	 * @date Aug 27, 2020 10:31:08 AM
	 */
	public  String upLoadFile(File file) {
		InputStream inputStream;
		StorePath storePath = null;
		try {
			inputStream = new FileInputStream(file);
			storePath = storageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()),
					null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return getResAccessUrl(storePath);
	}

	

	

	/**
	 * 
	 * @description return the address of the uploaded file
	 * @author feifei.yuan
	 * @param storePath
	 * @return String
	 * @date Aug 27, 2020 10:32:32 AM
	 */
	public  String getResAccessUrl(StorePath storePath) {
		String fileUrl = storePath.getFullPath();
		return fileUrl;
	}

	/*
	 * why the next tow  functions need to add lock?
	 * <p>
	 * In the case of concurrency, deleting files and downloading files will cause IO exceptions
	 * <p>
	 * 
	 * <p>
	 * There is no high concurrency problem here, but it may be due to network reasons 
	 * or the file download or delete time is too long, the last operation has not been completed,
	 * the next operation is coming, at this time you need to lock to ensure that there is 
	 * no concurrency security
	 * <p>
	 * <p>
	 * Don't ask me why I know, I just know.
	 * <p>
	 */
	
	
	/**
	 * 
	 * @description delete the file based the given fileUrl
	 * @author feifei.yuan
	 * @param fileUrl: the file will be deleted on the fastdfs server path
	 * @return void
	 * @date Aug 27, 2020 10:32:47 AM
	 */
	public synchronized  void  deleteFile(String fileUrl) {
		if (StringUtils.isEmpty(fileUrl))
			return;
		StorePath storePath = StorePath.praseFromUrl(fileUrl);
		
		storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
	}

	
	/**
	 * 
	 * @description  download file form fastdfs
	 * @author       fefei.yuan
	 * @param        group:   the fastdfs group 
	 *               path:    the file path 
	 * @return       byte[]    
	 * @date         Aug 28, 2020 5:37:28 PM
	 */
	public void   downLoadFile(HttpServletResponse response, String fileUrl, String fileName) {
		ReentrantLock lock = new ReentrantLock();
		lock.lock();
		byte[] bs = null;
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			StorePath storePath = StorePath.praseFromUrl(fileUrl);
			bs = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
			response.getOutputStream().write(bs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

非非也是第一次使用FastDFS,里面踩了很多坑呢,希望我写的文章可以帮助到大家少踩坑,后续我会出一篇FastDFS+Nginx+FastDFS_Nginx_Moudle的服务器配置,大家敬请期待。

码字不易,动动你们的小手指,给非非一个赞吧,你们的给力就是我写作的动力,我是袁非非!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastDFS 是一个开源的轻量级分布式文件系统,它主要解决了海量文件存储问题,具有高性能、高可靠性、易扩展性等特点。下面介绍一下 FastDFS文件上传删除和预览操作。 1. 文件上传 FastDFS文件上传分为两步,第一步是上传文件到 FastDFS 服务器,第二步是保存文件元数据到数据库中。 上传文件到 FastDFS 服务器: ```python import os from fdfs_client.client import Fdfs_client # 定义 FastDFS 配置文件路径 FDFS_CLIENT_CONF = '/etc/fdfs/client.conf' # 创建 Fdfs_client 对象 client = Fdfs_client(FDFS_CLIENT_CONF) # 上传本地文件 ret = client.upload_by_filename('/path/to/local/file') if ret.get('Status') == 'Upload successed.': # 获取文件 ID file_id = ret.get('Remote file_id') else: # 上传失败 file_id = None ``` 保存文件元数据到数据库中: ```python from sqlalchemy.orm import sessionmaker from models import File from database import engine # 创建数据库连接 Session = sessionmaker(bind=engine) session = Session() # 创建文件对象并保存到数据库中 file = File(file_id=file_id, filename='example.txt', size=os.path.getsize('/path/to/local/file')) session.add(file) session.commit() ``` 2. 文件删除 FastDFS 的文件删除也分为两步,第一步是删除 FastDFS 服务器上的文件,第二步是从数据库中删除文件元数据。 删除 FastDFS 服务器上的文件: ```python from fdfs_client.client import Fdfs_client # 创建 Fdfs_client 对象 client = Fdfs_client(FDFS_CLIENT_CONF) # 删除文件 ret = client.delete_file(file_id) if ret == 0: # 删除成功 pass else: # 删除失败 pass ``` 从数据库中删除文件元数据: ```python from sqlalchemy.orm import sessionmaker from models import File from database import engine # 创建数据库连接 Session = sessionmaker(bind=engine) session = Session() # 获取文件对象并从数据库中删除 file = session.query(File).filter_by(file_id=file_id).first() if file: session.delete(file) session.commit() ``` 3. 文件预览 FastDFS 的文件预览需要在客户端下载文件并提供预览功能,具体实现方式根据业务需求而定。例如,可以使用 Flask 框架提供 Web 服务,通过浏览器访问预览页面。 ```python from flask import Flask, send_file from fdfs_client.client import Fdfs_client # 创建 Flask 应用 app = Flask(__name__) # 定义 FastDFS 配置文件路径 FDFS_CLIENT_CONF = '/etc/fdfs/client.conf' @app.route('/preview/<file_id>') def preview(file_id): # 创建 Fdfs_client 对象 client = Fdfs_client(FDFS_CLIENT_CONF) # 下载文件到本地 ret = client.download_to_buffer(file_id) if ret.get('Content') is not None: # 返回文件内容 return send_file(ret.get('Content'), attachment_filename='example.txt') else: # 下载失败 return 'Download failed.' if __name__ == '__main__': app.run() ``` 在浏览器中访问 http://localhost:5000/preview/{file_id} 即可预览文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值