文件上傳部分,直接上代碼:前端
def uploadfile(request): #上傳文件 if request.method == 'POST': handle_uploaded_file(request.FILES.getlist("myfile",None)) return HttpResponse("文件上傳成功") return HttpResponse("Failed") def handle_uploaded_file(files): if not os.path.exists('upload/'): os.mkdir('upload/') for file in files: # print file.name with open('upload/' + file.name, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk)
接收前端post過來的filelist,將其一一以二進制方式寫入到新文件中。python
至於文件下載,我選用打包成zip文件的方式,這須要用到zipfile模塊,因此要django
import zipfile
正式代碼以下:app
def downloadzipfile(request): rootdir = 'download' the_file_name = "yourzip.zip" z = zipfile.ZipFile(the_file_name, 'w',zipfile.ZIP_DEFLATED) for parent,dirnames,filenames in os.walk(rootdir): for file in filenames: z.write(rootdir + os.sep + file) z.close() response = StreamingHttpResponse(file_iterator(the_file_name)) response['Content-Type'] = 'application/zip' response['Content-Disposition'] = 'attachment; filename=yourzip.zip' return response def file_iterator(file_name, chunk_size=512): with open(file_name, 'rb') as f: while True: c = f.read(chunk_size) if c: yield c else: break
可將Django項目目錄下download文件夾裏的文件打包爲zip文件,並下載到本地,使用StreamingHttpResponse比HttpResponse更適合於文件的傳輸,不會因文件過大致使佔用內存過大而崩潰。post
有時文件有中文名會有bug,這種時候須要將代碼修改成以下模樣:測試
from django.utils.encoding import escape_uri_path from django.http import HttpResponse def test(request): file_name = '測試.txt' content = ... response = HttpResponse(content, content_type='application/octet-stream') response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name)) return response
Python文件打開方式:code
r : 以只讀方式打開文件,文件不存在則出錯orm
w:以只寫方式打開文件,文件存在則清空,不存在則創建ip
a:以追加只寫的方式打開,不清空文件,在文件末尾加入內容 內存
+: 有讀寫雙權限。
r只有讀的權限,w和a只有寫的權限,w清空文件,a不清空文件。(read, write,append)