最近用python的flask框架完成了一个最基本的文本文件上传,然后读取。
前端用的Angular的ng2-file-upload完成文件上传,后端用flask接收上传的文件,接着做处理。
在交互的过程中发现,当文本的编码格式不是UTF-8的时候(python3 默认的编码是UTF-8),会产生decode错误。
错误信息:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte
解决办法如下:
files = request.files['file'].read() files_charset = chardet.detect(files)# 获取文件的编码格式 article = files.decode(files_charset['encoding'])# 按照文件的的编码格式读取文件内容
前端Angular的ts如下:
import { Component, OnInit } from '@angular/core'; import { FileUploader } from 'ng2-file-upload'; import {Router} from '@angular/router'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; @Component({ selector: 'app-file', templateUrl: './file.component.html', styleUrls: ['./file.component.scss'] }) export class FileComponent implements OnInit { info = '点击这里选择文件'; formData = new FormData(); dataSource: Observable<any>; uploader: FileUploader = new FileUploader({url: '/api/file'}); constructor( private router: Router, private http: HttpClient ) { } ngOnInit() { } selectedFileOnChanged(event) { // 单文件上传,选择文件后显示文件名 if ( this.uploader.queue.length > 0 ) { const file = this.uploader.queue[0]._file; const fileName = this.uploader.queue[0]._file.name; this.formData.append('file', file, fileName); if ( fileName == '' ) { this.info = '点击这里选择文件'; } else { this.info = fileName; } } else { this.info = '点击这里选择文件'; } } submit() {// 上传文件 const headers = new HttpHeaders(); headers.set('Content-Type', 'multipart/form-data');// 上传类型为文件 headers.set('Accept', 'application/json');// 接收json文件 this.dataSource = this.http.post('/api/file', this.formData, { headers: headers} ); this.dataSource.subscribe( data =>{ console.log(data);//接收数据 }); } destroy() {// 清空文件缓存 this.uploader.clearQueue(); } }
前端HTML页面如下:
<div class="row" xmlns=""> <div class="col-md-12"> <nb-card> <nb-card-header> <h4>选择需要分析的文件:</h4> </nb-card-header> <nb-card-body> <div class="row high" ngForm> <div class="col-md-3 col-lg-3 col-sm-3"> <a href="javascript:void(0);" class="file btn btn-hero-success btn-sm" (click)="destroy()"> <input type="file" ng2FileSelect [uploader]="uploader"
(change)="selectedFileOnChanged($event)" accept=".pdf,.doc,.docx,.txt"
name="file" /> {{ info }} </a> </div> <div class="col-md-2 col-lg-2 col-sm-2"> <button type="submit" class="btn btn-hero-success btn-sm" (click)="submit()">提交文件</button> </div> <div class="col-md-7 col-lg-7 col-sm-7"> <span class="tip">提示:单文件分析,可传doc,docx,pdf,txt等文本文件。</span> </div> </div> </nb-card-body> </nb-card> </div> <router-outlet></router-outlet> </div>