0
点赞
收藏
分享

微信扫一扫

Django读取上传文件为Unicode如何转为文字并去除换行 - Python


前端Vue代码:

<form>
<input type="file" value="" id="file" accept=".doc,.docx,.txt" @change="getFile($event)">
<button @click="submitForm($event)">提交</button>
</form>

后端Django代码:

def index(request):
req = request.FILES.get('file')
# 将上传的文件逐行读取保存到list中
content = []
for line in req.read().splitlines():
content.append(line.decode("utf-8"))

  1. req为前端请求的文件对象
  2. ​req.read()​​ : 读取文件每行的内容
  3. ​splitlines()​​ : 消除换行
  4. ​line.decode("utf-8")​​ : 将每行内容的Unicode转换为 utf-8 编码. 即正常的中文显示

具体文件上传的代码请看: Vue+Django 实现文件上传, 数据交互, 文件类型过滤, 文本校验功能



举报

相关推荐

0 条评论