python 上传下载文件

最近刚学python,遇到上传下载文件功能需求,记录下!

django web项目,前端上传控件用的是uploadify。

文件上传 - 后台view 的 Python代码如下:

 1 @csrf_exempt
 2 @require_http_methods(["POST"])
 3 def uploadFiles(request):
 4     try:
 5         user = request.session.get('user')
 6         allFimeNames = ""
 7         #获取所有上传文件
 8         files = request.FILES.getlist("file")
 9         for file in files:
10             # 获取文件名 解析文件后缀 获取新文件名
11             oldName = file.name
12             filename = str(int(time.time() * 10))+"."+oldName.split(".")[1]
13             now = datetime.now()
14             filePath = os.path.join("developmentTask",str(user.get("userId"))+"-"+now.strftime('%Y-%m-%d'))
15             dirpath = os.path.join(settings.UPLOADFILES_DIRS , filePath)
16             #写入服务器
17             if not os.path.exists(dirpath):
18                 os.makedirs(dirpath)
19             newFilePath = os.path.join(dirpath, filename)
20             with open(newFilePath, 'wb+') as destination:
21                 for chunk in file.chunks():
22                     destination.write(chunk)
23             #返回新文件名 多个用逗号隔开
24             allFimeNames = os.path.join(filePath,filename)
25     except Exception:
26         return JsonResponse(data={'error': "系统异常"}, status=400)
27     return JsonResponse(data={'filePath': allFimeNames})

request.FILES.getlist("file")此处的file 是前端页面的文件提交的名称,可以在uploadify中配置。

文件下载:
 1 @csrf_exempt
 2 @require_http_methods(["GET"])
 3 def downloadFile(request):
 4     filePath = request.GET.get("filepath")
 5     fileName = request.GET.get("filename")
 6     file_name = os.path.join(settings.UPLOADFILES_DIRS, filePath)
 7     if os.path.exists(file_name):
 8         def file_iterator(file_name, chunk_size=512):
 9             with open(file_name) as f:
10                 while True:
11                     c = f.read(chunk_size)
12                     if c:
13                         yield c
14                     else:
15                         break
16         response = StreamingHttpResponse(file_iterator(file_name))
17         response['Content-Type'] = 'application/octet-stream'
18         response['Content-Disposition'] = 'attachment;filename="{0}"'.format(fileName)
19         return response
20     response = StreamingHttpResponse("文件不存在!")
21     response['Content-Type'] = 'application/octet-stream'
22     response['Content-Disposition'] = 'attachment;filename="{0}"'.format("")
23     return response

 

以上就是django上传下载的功能代码。

posted @ 2017-07-24 08:33  chanjuan  阅读(801)  评论(0编辑  收藏  举报