文件上传部分,直接上代码:前端
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)