python实现上传下载⽂件功能最近刚学python,遇到上传下载⽂件功能需求,记录下!
django web项⽬,前端上传控件⽤的是uploadify。
⽂件上传 - 后台view 的 Python代码如下:
@csrf_exempt
@require_http_methods(["POST"])
def uploadFiles(request):
try:
user = ('user')
allFimeNames = ""
#获取所有上传⽂件
files = list("file")
for file in files:
python新手代码userid
# 获取⽂件名解析⽂件后缀获取新⽂件名
oldName = file.name
filename = str(int(time.time() * 10))+"."+oldName.split(".")[1]
now = w()
filePath = os.path.join("developmentTask",("userId"))+"-"+now.strftime('%Y-%m-%d'))
dirpath = os.path.join(settings.UPLOADFILES_DIRS , filePath)
#写⼊服务器
if not ists(dirpath):
os.makedirs(dirpath)
newFilePath = os.path.join(dirpath, filename)
with open(newFilePath, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
#返回新⽂件名多个⽤逗号隔开
allFimeNames = os.path.join(filePath,filename)
except Exception:
return JsonResponse(data={'error': "系统异常"}, status=400)
return JsonResponse(data={'filePath': allFimeNames})
list("file")此处的file 是前端页⾯的⽂件提交的名称,可以在uploadify中配置。⽂件下载:
@csrf_exempt
@require_http_methods(["GET"])
def downloadFile(request):
filePath = ("filepath")
fileName = ("filename")
file_name = os.path.join(settings.UPLOADFILES_DIRS, filePath)
if ists(file_name):
def file_iterator(file_name, chunk_size=512):
with open(file_name) as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
response = StreamingHttpResponse(file_iterator(file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(fileName)
return response
response = StreamingHttpResponse("⽂件不存在!")
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format("")
return response
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。