一、文件上传
# 注意点1:需要过滤掉文件名中的中文字符,否则无法正常保存
newFileName = filter_chinese_and_punctuation_exclude_dot(newFileName)
path = os.getcwd() + settings.MEDIA_URL + settings.AUDIO_URL + newFileName
# 根据路径打开指定的文件(以二进制读写方式打开)
fw = open(path, 'wb+')
# 注意点2:chunks将对应的文件数据转换成若干片段, 分段写入, 可以有效提高文件的写入速度, 适用于2.5M以上的文件
for chunk in oriFile.chunks():
fw.write(chunk)
fw.close()
print("文件上传成功," + path)
二、txt文件下载
# 定义下载方法
def exportTxt(request):
# 注意点3:这里若用Content-Type='text/plain',则导出的内容显示在浏览器
# response = HttpResponse(Content-Type='text/plain')
# 用'application/octet-stream',则导出txt文件下载
response = HttpResponse(content_type='application/octet-stream')
# 注意点4:若导出的文件名包含中文,则会导致文件名不符合预期结果(实际测试时,文件名变成了方法名),需要使用escape_uri_path方法对文件名进行处理。
response['Content-Disposition'] = 'attachment;filename{}'.format(escape_uri_path(filename))
response.write("txt内容1\n")
response.write("txt内容2\n")
return response