以前隨筆過一篇Docker來搭建分佈式文件系統FastDfs就跳過了html
http://www.javashuo.com/article/p-dbuqjqaz-w.html數據庫
1.安裝依賴django
#安裝庫 pip install py3Fdfs pip install mutagen pip isntall requests
2.配置settings.py服務器
# 激活重寫存儲文件引擎方法 DEFAULT_FILE_STORAGE = 'utils.fdfs.storage.FDFSStorage' # 圖片存阿里雲的地址 FDAS_URL = 'http://39.97.117.229:8888/' # 存進阿里雲服務器裏由於沒有後綴(jpg/png),圖片鏈接要放進 img 標籤裏才能顯示 # <img src="http://39.106.64.101:8888/group1/M00/00/00/rBHmx10A9JmAVEKNAABf71XWOL06003319" alt=""># 配置 Fastdfs 配置文件 FDFS_CLIENT_CONF = os.path.join(BASE_DIR, 'client.conf')
3.配置client.conf 文件分佈式
connect_timeout=30 network_timeout=60 tracker_server=39.97.117.229: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
4.封裝上傳文件 fastdfs.pyide
from django.core.files.storage import Storage from fdfs_client.client import Fdfs_client,get_tracker_conf from video_back.settings import FDAS_URL,FDFS_CLIENT_CONF # 重寫存儲引擎方法 class FastDfsStroage(Storage): def __init__(self, base_url = None, client_conf = None): """ 初始化對象 :param base_url: :param client_conf: """ if base_url is None: base_url = FDAS_URL # 'http://39.106.64.101:8888/' self.base_url = base_url if client_conf is None: client_conf = FDFS_CLIENT_CONF # FDFS_CLIENT_CONF = os.path.join(BASE_DIR, 'client.conf') self.client_conf = client_conf def _open(self, name, mode = 'rb'): """ 打開文件 :param name: :param mode: :return: """ pass def _save(self,content): """ 保存文件 :param name: 傳入文件名 :param content: 文件內容 :return:保存到數據庫中的FastDFSDE文件名 """ client = Fdfs_client(get_tracker_conf(FDFS_CLIENT_CONF)) ret = client.upload_by_buffer(content.read()) if ret.get("Status") != "Upload successed.": raise Exception("upload file failed") file_name = ret.get("Remote file_id") #byte轉str file_name = str(file_name,encoding = "utf-8") return file_name def exists(self, name): """ 檢查文件是否重複, FastDFS自動區分重複文件 :param name: :return: """ return False def url(self, name): """ 獲取name文件的完整url :param name: :return: """ return self.base_url + name
5.上傳邏輯views.py阿里雲
#導入封裝類 from .fastdfs import * from django.http import JsonResponse def upload(request): img = request.FILES.get('file') img_fast = FastDfsStroage() #存入遠程服務器 ret = img_fast._save(img) #返回存入圖片的url url = img_fast.url(ret) if url: return JsonResponse({'url':url})
效果以下:url