我正在尝试上传和图像使用Bootstrap-Vue表单文件输入,并通过POST发送到Flask后端使用Axios库,然后存储在一个文件夹中。
我的问题是Flask在"request.files“中找不到”文件“。我很确定我犯了个新手的错误。
这是我的代码:
前端:
<template>
<div class="mx-5 container-fluid">
<div class="mx-5 row">
<div class="col-sm-10">
<b-form-file
type="file"
id="file"
v-model="file"
:state="Boolean(file)"
ref="file"
placeholder="Choose a file or drop it here..."
drop-placeholder="Drop file here..."
v-on:change="submitFile"
></b-form-file>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
};
},
methods: {
submitFile() {
/* Initialize the form data */
const path = 'http://localhost:5000/single-file';
const formData = new FormData();
/* Add the form data we need to submit */
formData.append('file', this.file);
/* Make the request to the POST /single-file URL */
axios.post(path,
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}).then(() => {
// console.log('SUCCESS!!');
})
.catch(() => {
// console.log('FAILURE!!');
});
},
},
};后端:
from flask import Flask, jsonify, request, send_file, redirect, url_for
from werkzeug.utils import secure_filename
import os
# configuration
DEBUG = True
UPLOAD_FOLDER = '/images'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
@app.route('/single-file', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
print('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
print('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('download_file', name=filename))
return ''
if __name__ == '__main__':
app.run()我得到HTTP代码302 (重定向),并在控制台中打印“无文件部分”。
任何帮助都是非常感谢的。
发布于 2021-11-22 12:04:52
我在你的代码中看不到明显的错误,看起来请求是从你的前端和后端正确传递过来的。
在这种情况下,我建议使用Postman来解耦前端和后端。如果您在使用Postman时得到正确的响应,您可以缩小范围,即错误出现在前端、浏览器或与axios有关的干扰请求数据的某些方面。
另外,尝试获取一条错误消息,或者打印为什么flask认为“文件”不在request.files中,如果一切正常,它应该在那里
https://stackoverflow.com/questions/70062530
复制相似问题