python學習之文本文件上傳


最近用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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM