如何从Angular向Flask服务器发出POST请求

时间:2020-03-09 01:08:02

标签: python angular flask

我正在开发一个需要从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>  

这是我的组件。

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'

1 个答案:

答案 0 :(得分:0)

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