我正在尝试将VueJS客户端上的from上载到Flask服务器。我正在发送包含其他表单字段的FormData中的图像。我可以访问其他表单字段。然而,无论发送到我的服务器的是什么,似乎都无法保存在我的flask应用程序中。如果有帮助,数据将作为不可变的多字典发送到我的api。
Vuejs
<template>
<ValidationObserver v-slot="{ handleSubmit }">
<b-form @submit.prevent="handleSubmit(onSubmit)" enctype="multipart/form-data">
<ValidationProvider rules="required" v-slot="{ errors }">
<b-form-group
id="price-group"
label="Price:"
label-for="price-input"
>
<b-form-input
id="price-input"
v-model="productForm.price"
type="text"
required
placeholder="Enter price of the product..."
></b-form-input>
</b-form-group>
<span>{{ errors[0] }}</span>
</ValidationProvider>
<b-button-group>
<b-button
type="submit" variant="primary">Submit</b-button>
</b-button-group>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
productForm: {
price: '',
image_set: {
coverphoto: null,
},
showMessage: false,
notification: '',
},
coverphotoURl: '',
};
},
methods: {
createProduct(payload) {
const path = 'http://127.0.0.1:5000/new_products';
axios.post(path, payload)
.then(() => {
this.showMessage = true;
this.notification = 'Registration Successful';
})
.catch(() => {
this.showMessage = true;
this.notification = payload;
});
},
initForm() {
this.productForm.price = '';
this.productForm.image_set.coverphoto = null;
},
onSubmit() {
const payload = new FormData();
payload.append('price', this.productForm.price);
payload.append('coverphoto', this.productForm.image_set.coverphoto, this.productForm.image_set.coverphoto.name);
this.createProduct(payload);
},
onFileChange(e) {
const file = e.target.files[0];
this.productForm.image_set.coverphoto = file;
this.coverphotoURl = URL.createObjectURL(file);
},
</script>
烧瓶文件
@app.route('/new_products', methods=['POST'])
def new_products():
if request.method == 'POST':
data = request.form
if request.files:
images = request.files.getlist('coverphoto')
else:
return jsonify({'message' : 'No File Uploaded'})
print(images) # Print images will return [<FileStorage: 'Coffee Roasters.jpg' ('image/jpeg')>]
newProduct = Products(str(uuid.uuid4()), data['name'], data['tasting_notes'], data['origination'], data['pairing'], data['price'])
try:
db.session.add(newProduct)
db.session.commit()
filename = secure_filename('coverphoto.jpg')
img_path = os.path.join('/',app.config['UPLOAD_FOLDER'], filename)
images.save(img_path)
new_img = Images(str(uuid.uuid4()), img_path, newProduct.id)
db.session.add(new_img)
db.session.commit()
return jsonify({'message' : 'Upload Successful'})
except:
return jsonify({'message' : 'Upload Unsuccessful'})
我如何才能将[<;FileStorage:'Coffee broasters.jpg'('image/jpeg')>;]转换为flask能够保存的内容?谢谢你的帮助
我想您应该在Axios中设置适当的头,以便能够在服务器上检索文件。 使用以下命令:
相关问题 更多 >
编程相关推荐