from django.http import HttpResponse
from chardet import detect
def dofiles(request):
'''
:param request: 用户上传的文件
:return: 文件内容
'''
if request.method == 'POST':
dirlist = request.FILES.get('pathname',None)
if not dirlist:
return HttpResponse('file not found')
#被我保存到本地啦,保存到哪里随意啦
save_path = 文件路径\\%s'%(dirlist.name)
with open(save_path,'wb+') as f:
for chunk in dirlist.chunks():
f.write(chunk)
#文件读取,之前读取字符串乱码,所以导入了chardet模块
txt_content = dirlist.read()
txt_charinfo = detect(txt_content)
txt_read_decode = txt_content.decode(txt_charinfo['encoding'])
return HttpResponse(txt_read_decode)
总结一下自己今天出现并解决的疑问
1、request.FILES获取的是一个文件对象
print(type(dir)) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
# 上传文件的处理对象的类型 (根据文件大小决定返回哪种类型):
# <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> (内存中:2.5M以下)
# <class 'django.core.files.uploadedfile.TemporaryUploadedFile'> (临时文件中:2.5M以上)
这个对象有各种属性:
dirlist.name #获取的是文件名
dirlist.size #获取文件长度
dirlist.read() #获取文件内容