@staticmethod
def upload_base64_file(base64_obj, dst_file_path=settings.UPLOAD_DEFAULT_FOLDER, file_ext=".jpg"):
"""
上传base64文件流到服务器指定目录
:param dst_file_path: 文件存放路径 "tmp/"
:param base64_obj: base64流对象
:param file_ext: 新文件扩展名:默认.jpg
:return: 文件上传存入的文件目录
"""
ret = {'status': False, 'msg': ''}
try:
# 将base64转成文件流对象
file_str = base64_obj.split(',')[1].encode('utf-8')
file_data = base64.b64encode(file_str)
# 当前时间戳:年月日时分秒
cur_time = int(round(time.time() * 1000))
# 拼接新的文件名
file_name = "%s%s" % (cur_time, file_ext)
# 拼接文件存放目录
file_path = "%s/%s" % (settings.MEDIA_ROOT, dst_file_path)
save_path = "%s%s%s" % (dst_file_path, file_name, file_ext)
# 判断文件目录
FileOperateUtil.validate_folder_exists(file_path, is_create=True)
try:
# 拼接文件最终存放全路径
real_path = "%s%s" % (file_path, file_name)
# 上传文件操作
destination = open(real_path, 'wb+')
# 写入文件
destination.write(file_data)
ret = {'status': 200, 'msg': '上传成功', 'file_path': save_path}
except Exception as e:
log.debug("上传base64文件,写文件发生异常,%s" % e)
raise Exception("上传base64文件,写文件发生异常")
finally:
destination.close()
except Exception as e:
log.debug("上传base64文件发生异常,%s" % e)
ret = {'status': 500, 'msg': e}
return ret
@staticmethod
def download_batch_file(src_file_folder, zip_folder=settings.ZIP_DEFAULT_FOLDER, down_file_name=None, is_delete=True):
"""
将文件夹压缩打包下载
:param src_file_folder: 要下载的文件目录
:param zip_folder: 打包存放目录
:param down_file_name: 下载时指定文件名
:param is_delete: 下载完成后是否删除打包的文件,默认:删除
:return: 带有文件流的response响应
"""
# 判断待打包目录是否存在,不存在则抛出异常
FileOperateUtil.validate_folder_exists(src_file_folder)
# 判断打包存放目录是佛存在,不存在则新建
FileOperateUtil.validate_folder_exists(zip_folder, is_create=True)
# 设置响应头
if os.path.exists(src_file_folder):
cur_time = int(round(time.time() * 1000))
zip_file_name = "%s" % cur_time
zip_file_path = "%s/%s" % (settings.MEDIA_ROOT, zip_folder, zip_file_name)
# 打包该目录
FileOperateUtil.zip_dir(src_file_folder, zip_file_path)
# 判断打包生成的文件是否是个文件
if os.path.isfile(zip_file_path):
filename = os.path.basename(zip_file_path)
# 若未指定下载文件名,则已文件本身名称为准
if down_file_name is None:
down_file_name = filename
# 读取文件流,并构造请求响应
response = HttpResponse(FileOperateUtil.file_iterator(zip_file_path))
response['Content_type'] = "application/octet-stream"
response['Content-Disposition'] = 'attachment; filename={0}'.format(down_file_name.encode('utf-8'))
else:
response = HttpResponse("下载失败,不是一个文件!", content_type="text/plain;charset=utf-8")
else:
response = HttpResponse("文件不存在,下载失败!", content_type="text/plain;charset=utf-8")
return response |