v1.0
v1.1 更正为,Fastdfs的python api还算是可以的,只是不是官方出的。
前言:
前段时间被朋友拖住了,他说最近打算实现一个文件分享的网站,一个是图片,一个是特定的文件,比如压缩包、pdf这类的。 他个人是做idc的,手里的资源还是不少的, 想通过文件分享网站来导入点所谓的流量。哥年轻时跟他搞过一个php的淘宝图片站,结果有个卖衣服的站点,流量很大,成本太高了,再说也没钱再次投入了,就那么放弃Le ~ 没赚多少钱,倒是赔给那几个淘宝卖家100多块钱 ~ 想起往事,还算有趣的 ~
现在的我以前不是当初菜鸟的我了,google了半天,从别地方,拔下来一个html模板,而且还是很高端的样子,后端是用pyton的tornado框架改了改,跑了几个实例都是没有问题的 ~
这里标注下,文章的原文地址 blog.xiaorui.cc
实现的方法简单的
上传
建立表单,文件上传,然后写如到tmp目录的下,调用自己写的python fastdfs模块上传文件。也可以放到目录后,用inotify 来做文件的监控,触发文件后,就上传到fastdfs分布式存储里面。
(修正,python是有合适的Fastdfs读写模块的。 )
# -*- coding:utf-8 -*-
from fdfs_client.client import *
import time
client_file='client.conf'
test_file='test.txt'
download_file='test2.txt'
try:
client = Fdfs_client(client_file)
#upload
ret_upload = client.upload_by_filename(test_file)
print ret_upload
time.sleep(5) #等待5s,否则下载时会报错文件不存在
file_id=ret_upload['Remote file_id'].replace('\\','/') #新版本文件存放Remote file_id格式变化
#download
ret_download=client.download_to_file(download_file,file_id)
print ret_download
#delete
ret_delete=client.delete_file(file_id)
print ret_delete
except Exception,ex:
print ex
下载
可以通过fastdfs本身的web做下载连接,但是为了更高的性能,推荐使用nginx fastdfs模块来实现的下载,给朋友也是这么做的。
(还没有正式的上线,嘿嘿)
subprocess 调用系统的fastdfs客户端
上传文件:/usr/local/bin/fdfs_upload_file <config_file> <local_filename>
下面是Tornado的POST文件模式
def post(self):
upload_path=os.path.join(os.path.dirname(__file__),'files') #文件的暂存路径
file_metas=self.request.files['file'] #提取表单中‘name’为‘file’的文件元数据
for meta in file_metas:
filename=meta['filename']
filepath=os.path.join(upload_path,filename)
with open(filepath,'wb') as up: #有些文件需要已二进制的形式存储,实际中可以更改
up.write(meta['body'])
self.write('finished!')
app=tornado.web.Application([
(r'/file',UploadFileHandler),
])

一般来说,上传后得到的文件名字,是一串hash,和以前的名字比起来不太一样。
举个例子,我明明上传的文件时 xiaorui.jpg,结果fastdfs接口给我返回的是 一堆的hash ,这是在让人有点小郁闷。
我这里还只是图片的应用,后期文件功能出来后,让人看到的都是hash,你都不能通过hash想象出他的文件。
查看了uc那边的技术博客,扩展了一套简单的路子。
这边用到的是 nginx tornado jquery bootstrap
1. 应用系统在上传文件到FastDFS成功时将原始文件名和“文件索引(FID)”保存下来,我这里会记录在redis里面。
2. 在浏览器下载的时用Nginx的域名和FID拼出url,在url后面增加一个参数,指定原始文件名。例如:xxx.xx.xx.xx/group2/M00/00/89/eQ6h3FKJf_PRl8p4AUz4wO8tqaA688.apk?attname=xiaorui.cc
3. 在Nginx上进行如下配置,这样Nginx就会截获url中的参数attname,在Http响应头里面加上字段 Content-Disposition “attachment;filename=$arg_attname”。
location /group1/M00 {
root /data/store/data1;
if (arg_attname ~ "^(.*).cc") {
add_header Content-Disposition "attachment;filename=arg_attname";
}
ngx_fastdfs_module;
}
location /group2/M00 {
root /data/store/data2;
if (arg_attname ~ "^(.*).cc") {
add_header Content-Disposition "attachment;filename=arg_attname";
}
ngx_fastdfs_module;
}
4. 浏览器发现响应头里面有Content-Disposition “attachment;filename=$arg_attname”时,就会把文件名显示成filename指定的名称。
大家可以测试下,原来就是给用户的url多出一个get参数,用nginx识别到之后,插入到header头信息Content-Disposition 协议。
到半夜为止,和哥们一块已经实现了该项目的大部门网络框架,当然前端的nginx
是用kvm虚拟机做的,毕竟7层对io需求不是很大。针对nginx做的轮训是在代码
层面实现的。
好了,就这样吧。 这fastdfs真是个好东西 ! 特别适合以文件为载体的在线服务,如图片站,文件分享等等 ! 但是问题是没有原生的python api,上传的时候,我每次还需要调用fastdfs来搞,实在麻烦。
