diango上传文件及去重
#上传文件
class UploadFile(APIView):
def post(self,request):
#接收参数
img = request.FILES.get("file")
# 获取当前时间
times = timezone.now()
# print(times)
#定义MD5对象
md5 = hashlib.md5()
#转码
md5.update(str(times).encode())
times_now = md5.hexdigest()
#把文件名和 当前时间组合
names = str(times_now) + str(img.name)
#建立文件流对象
f = open(os.path.join(UPLOAD_ROOT,'',names),'wb')
#写入服务器端
for chunk in img.chunks():
f.write(chunk)
f.close()
#返回文件名
return Response({
'code':200,
"message":'上传成功',
'img_name':names
})
settings配置
#settings.py
#配置上传图片路径
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# 定义上传文件夹的路径
UPLOAD_ROOT = os.path.join(BASE_DIR, 'static/upload')
django上传图片,去重以及加水印
#上传文件
class Myfile(View):
#生成随机汉字
def GBK2312(self):
#gbk2312对字符的编码采用俩个字节相组合,第一字节范围是0xb0,0xf7
head = random.randint(0xb0, 0xf7)
#第二字节范围是0xA1,0xfe
body = random.randint(0xa1, 0xfe)
#获取字节码
val = f'{head:x} {body:x}'
#转码 以gbs2312进行编码,获取bytes类型的字符串
str = bytes.fromhex(val).decode('gb2312')
return str
def post(self,request):
#获取参数
files = request.FILES.get('files')
print(files)
# 取相同名字覆盖
# 获取当前时间
times = timezone.now()
# print(times)
#定义MD5对象
md5 = hashlib.md5()
#转码
md5.update(str(times).encode())
times_now = md5.hexdigest()
#把文件名和 当前时间组合
files_name = str(times_now) + str(files.name)
# print(files_name)
#保存文件到本地
with open(os.path.join(UPLOAD_ROOT,'',files_name),'wb') as f:
for chunk in files.chunks():
f.write(chunk)
# #给图片上水印
# #打开图片
im = Image.open('./static/upload/'+str(files_name))
#生成画笔
draw = ImageDraw.Draw(im)
#定义字体
my_font = ImageFont.truetype(font="C:\\Windows\\Fonts\simsun.ttc",size=30)
#获取随机字体
text_str = self.GBK2312()
# print(text_str)
#修改
draw.text((0,0), text=text_str ,fill=(76,234,124,180),font=my_font)
#覆盖图片
im.save(os.path.join(UPLOAD_ROOT,"",files_name))
return HttpResponse(json.dumps({"message":files_name},ensure_ascii=False),content_type="application/json")