上一篇文章中(https://www.cnblogs.com/lutt/p/10640412.html),我們以圖片文件夾+圖片名字的方式來儲存圖片,這樣的做法會導致有重名的圖片會導致之前的圖片被覆蓋,解決這一問題的方法:MD5時間戳,圖片名稱可能會重復,但是上傳圖片的時間生成的MD5字符串是唯一的,可以以此來作為圖片保存的方式,就避免了圖片重名導致覆蓋的慘劇,下面來碼一段詳細的代碼:
from django.utils import timezone # 獲取當前時間 import hashlib # 給當前時間編碼 def pic_upload(request): if request.method == "GET": return render(request,"helloapp/pic_upload.html",locals()) if request.method == "POST": error = "" fp = request.FILES.get("file") # fp 獲取到的上傳文件對象 if fp: time_now = timezone.now() # 獲取當前日期時間 print(time_now) # 2019-04-03 00:51:21.225391+00:00 當前打印的時間格式是這樣,不能直接使用,需要用MD5編碼 m = hashlib.md5() m.update(str(time_now).encode()) # 給當前時間編碼 time_now = m.hexdigest() print(time_now) # ec3b25c7e44ded02d092c57dded2d5eb 此時為編碼后的時間 path = os.path.join(STATICFILES_DIRS[0],'image/' + time_now + fp.name) # 上傳文件本地保存路徑 # fp.name #文件名 #yield = fp.chunks() # 流式獲取文件內容 # fp.read() # 直接讀取文件內容 if fp.multiple_chunks(): # 判斷上傳文件大於2.5MB的大文件 # 為真 file_yield = fp.chunks() # 迭代寫入文件 with open(path,'wb') as f: for buf in file_yield: # for情況執行無誤才執行 else f.write(buf) else: print("大文件上傳完畢") else: with open(path,'wb') as f: f.write(fp.read()) print("小文件上傳完畢") models.ImgPath.objects.create(path=('image/' + time_now + fp.name)) else: error = "文件上傳為空" return render(request,"helloapp/pic_upload.html",locals()) return redirect(reverse("picindex") )# 重定向到首頁