前端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"))
- req为前端请求的文件对象
req.read()
: 读取文件每行的内容splitlines()
: 消除换行line.decode("utf-8")
: 将每行内容的Unicode转换为 utf-8 编码. 即正常的中文显示
具体文件上传的代码请看: Vue+Django 实现文件上传, 数据交互, 文件类型过滤, 文本校验功能