python實現(xiàn)上傳下載文件功能
更新時間:2020年11月19日 15:09:19 作者:chanjuan
這篇文章主要為大家詳細介紹了python實現(xiàn)上傳下載文件功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
最近剛學python,遇到上傳下載文件功能需求,記錄下!
django web項目,前端上傳控件用的是uploadify。
文件上傳 - 后臺view 的 Python代碼如下:
@csrf_exempt @require_http_methods(["POST"]) def uploadFiles(request): try: user = request.session.get('user') allFimeNames = "" #獲取所有上傳文件 files = request.FILES.getlist("file") for file in files: # 獲取文件名 解析文件后綴 獲取新文件名 oldName = file.name filename = str(int(time.time() * 10))+"."+oldName.split(".")[1] now = datetime.now() filePath = os.path.join("developmentTask",str(user.get("userId"))+"-"+now.strftime('%Y-%m-%d')) dirpath = os.path.join(settings.UPLOADFILES_DIRS , filePath) #寫入服務(wù)器 if not os.path.exists(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': "系統(tǒng)異常"}, status=400) return JsonResponse(data={'filePath': allFimeNames})
request.FILES.getlist("file")此處的file 是前端頁面的文件提交的名稱,可以在uploadify中配置。
文件下載:
@csrf_exempt @require_http_methods(["GET"]) def downloadFile(request): filePath = request.GET.get("filepath") fileName = request.GET.get("filename") file_name = os.path.join(settings.UPLOADFILES_DIRS, filePath) if os.path.exists(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
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python select及selectors模塊概念用法詳解
- Python連接HDFS實現(xiàn)文件上傳下載及Pandas轉(zhuǎn)換文本文件到CSV操作
- 完美解決python針對hdfs上傳和下載的問題
- Python selenium文件上傳下載功能代碼實例
- 基于python實現(xiàn)FTP文件上傳與下載操作(ftp&sftp協(xié)議)
- Python Socketserver實現(xiàn)FTP文件上傳下載代碼實例
- python3 requests庫文件上傳與下載實現(xiàn)詳解
- 使用Python操作FTP實現(xiàn)上傳和下載的方法
- python ftp 按目錄結(jié)構(gòu)上傳下載的實現(xiàn)代碼
- python實現(xiàn)的簡單FTP上傳下載文件實例
- python 基于selectors庫實現(xiàn)文件上傳與下載
相關(guān)文章
翻轉(zhuǎn)數(shù)列python實現(xiàn),求前n項和,并能輸出整個數(shù)列的案例
這篇文章主要介紹了翻轉(zhuǎn)數(shù)列python實現(xiàn),求前n項和,并能輸出整個數(shù)列的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python利用CNN實現(xiàn)對時序數(shù)據(jù)進行分類
這篇文章主要為大家詳細介紹了Python如何利用CNN實現(xiàn)對時序數(shù)據(jù)進行分類功能,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-02-02