首页 > 解决方案 > 如何从 Angular 向 Flask 服务器发出 POST 请求

问题描述

我正在开发一个应用程序,该应用程序需要我从 Angular 前端将 csv 文件上传到 FLASK 服务器。我很难做到这一点。我如何将角度前端连接到后端烧瓶服务器。

这是我的 component.html

<div [hidden] = "submitted">
<form (ngSubmite) = "onSubmit()" action = "http://localhost:5000" method = "post" enctype="multipart/form-data">  
    <input type="file" name="file" />  
    <input type = "submit" value="Upload">  
</form>  

这是我的 component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})


export class UploadComponent implements OnInit {

submitted = false;

constructor() { }

onSubmit(){
this.submitted = true;

}

ngOnInit() {
}

}

这是我的烧瓶服务器

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/upload' , method = ['GET' ,'POST'])
def upload_File():

if request.method == 'POST':
    #check if the psot request has the file part
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    #if the user does not select file , browser alsos 
    #submite an empty part without filename
    if file.filename == ' ':
        flash('No selected file')

     filename = secure_filename(file.filename)
     file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
     #return render_template('success.html', name = filename) 
    return redirect(request.url)
   return 'File Uploaded'

标签: pythonangularflask

解决方案


  1. 导入HttpClientModuleAppModuleimports.
  2. 像这样注入HttpClient您的组件(稍后将该逻辑移动到服务中)constructor(private readonly http: HttpClient) {}
  3. 最后在您的提交方法中,您可以执行 http 请求this.http.post(url, body).subscribe()

推荐阅读