[英]problem with uploading data with flask Python
I'm new to flask and i am trying to upload files i have as attributes filename data and type(meaning extension of the file) this is my app.py code :我是烧瓶的新手,我正在尝试上传我拥有的文件作为属性文件名数据和类型(意味着文件的扩展名)这是我的 app.py 代码:
from fileinput import filename
from io import BytesIO
from optparse import Values
from typing import Any
from flask_cors import CORS, cross_origin
from flask import Flask , render_template, request , send_file, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api, Resource, reqparse
from werkzeug.utils import secure_filename
import os
app= Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONs'] = False
db = SQLAlchemy(app)
api = Api(app)
app.secret_key = "caircocoders-ednalan"
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'docx', 'pptx' , 'xlsx'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
class Upload(db.Model):
id=db.Column(db.Integer, primary_key=True)
filename = db.Column(db.String(50))
data = db.Column(db.LargeBinary)
type = db.Column(db.String(50))
def __init__(self, filename, data, type):
self.filename = filename
self.type = type
def json(self):
return {"id":self.id , "filename":self.filename , "type":self.type }
class ProductsView(Resource):
def get(self):
files = Upload.query.all()
return {f'Files':list(x.json() for x in files)}
api.add_resource(ProductsView, '/files')
@app.route('/views', methods=['GET'])
def views():
"""files = Upload.query.all()
return render_template('view.html', values=Upload.query.all())"""
files = Upload.query.all()
return jsonify({'Files': list(dict(id=x.id,data=str(x.data),filename=x.filename, type=x.type) for x in files )})
@app.route('/upload' , methods=['POST'])
def upload_file():
# check if the post request has the file part
if 'files[]' not in request.files:
resp = jsonify({'message' : 'No file part in the request'})
resp.status_code = 400
return resp
files = request.files.getlist('files[]')
errors = {}
success = False
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
type = os.path.splitext(filename)
file.type = type[1]
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
success = True
upload = Upload(filename=file.filename, type=file.type, data=file.read())
db.session.add(upload)
db.session.commit()
return f'Uploaded: {file.type}'
else:
errors[file.filename] = 'File type is not allowed'
if success and errors:
errors['message'] = 'File(s) successfully uploaded'
resp = jsonify(errors)
resp.status_code = 500
return resp
if success:
upload = Upload(filename=file.filename, type=file.type ,data=file.read())
db.session.add(upload)
db.session.commit()
"""return f'Uploaded: {file.filename}'"""
resp = jsonify({'message' : 'Files successfully uploaded'})
resp.status_code = 201
return resp
else:
resp = jsonify(errors)
resp.status_code = 500
return resp
@app.route('/file/<upload_id>')
def get(upload_id):
product = Upload.query.filter_by(id=upload_id).first()
if product:
return product.json()
return {'message':'Product id not found'},404
@app.route('/download/<upload_id>')
def download(upload_id):
upload = Upload.query.filter_by(id=upload_id).first()
return send_file(BytesIO(upload.data), attachment_filename=upload.filename , as_attachment=True)
@app.route('/delete/<upload_id>')
def delete(upload_id):
f = Upload.query.filter_by(id=upload_id).first()
if f:
db.session.delete(f)
db.session.commit()
return {'message':'Deleted'}
else:
return {'message':'File not found'},404
when I try to upload a file I get the success message but when i check my DB i get the file as null as the pic shows.当我尝试上传文件时,我收到了成功消息,但是当我检查我的数据库时,我得到的文件为空,如图所示。
I am lost, any help would be much appreciated Thank you!我迷路了,任何帮助将不胜感激谢谢!
You need to first base64 encode your file contents.您需要首先对文件内容进行 base64 编码。 Also you need to make sure the datatype in the database is BLOB
您还需要确保数据库中的数据类型是 BLOB
upload = Upload(filename=file.filename, type=file.type, data=base64.b64encode(file.read()))
Moreover, type is a python default keyword which is causing issue.此外, type 是导致问题的 python 默认关键字。 Rename it
重命名它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.