1.安装fdfs_client
《安装方法》
2.将/etc/fdfs/client.conf复制到windows项目下
配置client.conf
connect_timeout=30
network_timeout=60
base_path=windows中确实存在的目录存放log文件
tracker_server= 虚拟机的ip:22122
log_level=info
use_connection_pool = false
connection_pool_max_idle_time = 3600
load_fdfs_parameters_from_tracker=false
use_storage_id = false
storage_ids_filename = storage_ids.conf
http.tracker_server_port=80
3.使用python上传文件
存储文件方法
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client
class FdfsStorage(Storage):
"""fast dfs文件存储类"""
def __init__(self, client_conf=None, base_url=None):
"""初始化"""
if client_conf is None:
client_conf = './utils/fdfs/client.conf'
self.client_conf = client_conf
if base_url is None:
base_url = 'http://192.168.0.128:8888/'
self.base_url = base_url
def _open(self, name, mode='rb'):
"""打开文件时使用"""
pass
def _save(self, name, content):
"""
保存文件时使用
name:上传文件的名字
content:包含你上传文件内容的File对象
"""
client = Fdfs_client(self.client_conf)
res = client.upload_by_buffer(content.read())
if res['Status'] != 'Upload successed.':
raise Exception('上传文件到fast dfs失败')
filename = res['Remote file_id']
return filename
def exists(self, name):
"""django判断文件名是否可用"""
return False
def url(self, name):
"""django返回访问文件的url路径"""
return self.base_url + name
配置项目的settings文件(将django默认的存储方法设置为自定义的)
DEFAULT_FILE_STORAGE = 'utils.fdfs.storage.FdfsStorage'
|