使用angular来使上传文件起作用,并将flask作为后端服务器。 但是,当我尝试上传文件时,始终会收到错误消息。 这是代码。
HTML元素:
<input class="paper-trade__upload-button_hidden" type="file" id="csv-upload" name="file" accept=".csv" ngf-max-size="2MB" (change)="csvToArray($event)">
角度:
csvToArray(fileInput: any) {
const hotInstance = this.hotRegisterer.getInstance(this.instance);
let fileReaded = fileInput.target.files[0];
this.tradeCaptureService.uploadPaperTradeCSV('KGI',
fileReaded).subscribe();
}
请求正文:
uploadPaperTradeCSV(brokerName: string, file): Observable<Trade> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data',
}),
};
let formData: FormData = new FormData();
formData.append('file', file);
return this.http.post<Trade>(`${this.baseUrl}/trade/upload?broker_name=${brokerName}`, formData, httpOptions)
.pipe(
tap(data => console.log(data)),
);
}
后端代码(python):作为请求。提交要求,将文件数据作为表单数据发送
@hello.route('/upload', methods=['POST'])
@jwt_required
def import_trades():
if request.method == 'POST':
broker_name = request.args.get('broker_name', '')
data = request.form.get('file')
if 'file' not in request.files:
return jsonify({'fail': 'no file found'})
file = request.files['file']
if not file.filename:
return jsonify({'fail': 'no file selected'})
file_format = file.filename.split('.', 1)[1].lower()
allowed_extension = set(['csv'])
if file and file_format in allowed_extension:
filename = secure_filename(file.filename)
file_path = os.path.join(UPLOAD_FOLDER, filename)
file.save(file_path)
response = trade_orm.convert_file_data(broker_name, file_path)
if os.path.exists(file_path):
os.remove(file_path)
return response
else:
return jsonify({'fail': 'please input valid info'})
但是我尝试上传文件,它总是返回“找不到文件”消息。使用Postman发送请求时购买,它可以正常工作。我在这里停留了很长时间..... 任何帮助将不胜感激,谢谢您的帮助
答案 0 :(得分:1)
我终于找到了解决这个问题的方法,删除了uploadPaperTradeCSV()方法中的'const httpOptions = {}'人员,然后该方法就可以正常工作。因此新代码将是这样
uploadPaperTradeCSV(brokerName: string, file): Observable<Trade> {
let formData: FormData = new FormData();
formData.append('file', file);
return this.http.post<Trade>(`${this.baseUrl}/trade/upload?broker_name=${brokerName}`, formData, httpOptions)
.pipe(
tap(data => console.log(data)),
);
但我仍然不知道为什么...