Flask学习「二」(保存文件—按年,月,日递归创建文件夹分别保存)
这段时间比较忙,一周没有写博客了,今天晚上放松一下写个博客,本篇记录如何将上传的图片按照年月日分别创建对应的文件夹并分别保存对应的图片。
首先在Python中使用time模块处理时间,用os模块处理文件的,那么我们下面将会用到这两个模块。
废话不多说,代码如下:
# =====================================start=======================================#
@api.route('/upload')
class upload(Resource):
@api.expect(parser)
def post(self):
form = UploadForm().validate_for_api()
fname = request.files.get('files') # 获取上传的文件
if fname:
t = time.strftime('%Y%m%d%H%M%S') # 年月日/时分秒
year = time.strftime('%Y', time.localtime(time.time())) # 系统当前时间年份
month = time.strftime('%m', time.localtime(time.time())) # 月份
day = time.strftime('%d', time.localtime(time.time())) # 日期
name = t + '_' + fname.filename # 通过_拼接时间戳和文件名
path = r'/usr/local/var/www/tiny/' # 上传文件后nginx保存的路径
fileYear = year
fileMonth = fileYear + '/' + month
fileDay = fileMonth + '/' + day + '/'
if not os.path.exists(path+fileYear): # 创建“年“文件夹
os.mkdir(path+year)
os.mkdir(path+fileYear+'/'+month)
os.mkdir(path+fileYear+'/'+month + '/' + day)
else:
if not os.path.exists(path+fileYear+'/'+month): # 创建“月“文件夹
os.mkdir(path+fileYear+'/'+month)
os.mkdir(path+fileYear+'/'+month+ '/' + day)
else:
if not os.path.exists(path+fileYear+'/'+month+ '/' + day): # 创建“日“文件夹
os.mkdir(path+fileYear+'/'+month+ '/' + day)
new_fname = path + fileDay + name
fname.save(new_fname) # 保存文件到指定路径
‘’‘
上传文件
’‘’
upload_form = UploadUpdateForm()
upload_form.path.data = fileDay
upload_form.type.data = form.type.data
# upload_form = upload_form.validate_for_api()
result = Upload().get_obj_by_form(upload_form).save_or_update()
return jsonify({'url': 'http://192.168.1.1:8080/tiny/'+fileDay + name, 'tar_url':path + fileDay + name, 'success': 1, 'message': '图片上传成功'})
else:
return '{"msg": "请上传文件!"}
# =====================================end=======================================#
这样就完成了上传文件部分的代码编写。