I have an API to upload files in my flask application. It's uploading the file perfectly fine but when I try to get the file using the path of url which I got from my api, I am getting 404 file not found.
Here is my code.
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
def generate_unique_filename(filename):
_, ext = os.path.splitext(filename)
unique_filename = f"{uuid.uuid4().hex}{ext}"
path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
return unique_filename, path
#app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
if file:
filename, path = generate_unique_filename(file.filename)
file.save(path)
file_url = f"{request.host_url}{app.config['UPLOAD_FOLDER']}/{filename}"
return jsonify({'file_url': file_url}), 201
else:
return jsonify({'error': 'No file was uploaded.'}), 400
I want to get url of my uploaded file from my api that can be opened.
Related
from PIL import Image
import PyPDF2
tess.pytesseract.tesseract_cmd = r'C:\Users\szaid\AppData\Local\Programs\Tesseract-OCR\tesseract'
translator=Translator()
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__,
static_url_path='',
static_folder='static',
template_folder='template')
photos = UploadSet('photos', IMAGES)
pdf = UploadSet('pdf', DOCUMENTS)
app.config['DEBUG'] = True
app.config['UPLOAD_FOLDER']= 'images'
class Get(object):
def __init__(self, file): enter code here
if render_template('image.html'):
self.file = tess.image_to_string(Image.open(project_dir + '/images/'+ file))
elif render_template('pdf.html'):
self.file = PyPDF2.PdfFileReader(project_dir+'/pdff/'+ file)
And below, this is backend code to save the file in 'images' folder but its giving me an error.
I mean there is two different html pages and in both pages, there is an option to upload file and image. but dont know how to manage in flask...
#app.route('/pdf', methods=["GET","POST"])
def pdf():
if request.method == 'POST':
if 'pdf' not in request.files:
return 'there is no photo'
name1 = request.form['pdf-name'] + '.pdf'
pdf = request.files['pdf']
path = os.path.join(app.config['UPLOAD_FOLDER'], name1)
pdf.save(path)
TextObject = Get(name1)
return TextObject.file
return render_template('pdf.html')
error
You're getting this error because your path to the PDF file is wrong. You've added the file extension but the path is missing the file name. You also have a problem with your slashes in the path. A correct path would be like:
"D:\images\yourFileName.pdf"
I'm trying to upload a file to my REST API, and then save it in a directory.
It's running on the build in flask development server.
I get this error:
PermissionError: [Errno 13] Permission denied: 'uploads/'
Here is my code:
class Upload(Resource):
def post(self):
new_file = request.files['file']
new_file.save('uploads/', 'file_name')
I understand why I get this error, but I can't figure out how to change permissions. How is that done?
I'm on windows 7.
BR Kresten
Did you set app['UPLOAD_FOLDER'] = 'uploads'?
Here is what I thought better for your uploaded files:
home_dir = os.path.expanduser("~")
UPLOAD_FOLDER = os.path.join(home_dir, "upload")
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
class Upload(Resource):
def post(self):
new_file = request.files['file']
file_name = secure_filename(new_file.filename)
new_file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))
How to process the file which is uploaded by giving the file path to the python script and download the processed file ?
The code
#app.route("/upload", methods=['POST'])
def upload():
target = os.path.join(APP__ROOT, 'data/')
print(target)
if not os.path.isdir(target):
os.mkdir(target)
for file in request.files.getlist("file"):
filename = file.filename
print(filename)
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("downloads.html")
You need to return the file.
response = app.make_response(file)
response.headers["Content-Disposition"] = "attachment; filename=yourfile.csv"
return response
I have one question about url_for Unable to open files in python flask- 404 not found. but was marked duplicate.
My requirement is very simple. To create an href link in the main page pointing to a file in the output folder. I tried almost all threads in SO for the answer seems not working for me. Im very new to python . Please help. Below is a sample code i have tried
from flask import Flask, redirect, url_for,send_from_directory
app = Flask(__name__)
#app.route('/main')
def index():
print 'test'
return '''Open file'''
#app.route('/out/<filename>')
def uploaded_file(filename):
print filename
return send_from_directory('./out/',
filename)
#app.route('/out/<filename>')
def uploaded_file2(filename):
print filename
return './out/'+filename
if __name__ == '__main__':
app.run(debug = True)
your app directory structure should be like this so this code would work. If the filename was not found in out folder then you will see "url not found":
app/
app.py
static/
out/
a.txt
templates/
index.html
from flask import Flask, render_template, redirect, url_for,send_from_directory
app = Flask(__name__)
app.config.update(
UPLOAD_FOLDER = "static/out/"
)
#app.route('/main')
def index():
print ('test')
return render_template('index.html')
#app.route('/out/<filename>')
def uploaded_file(filename):
print (filename)
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
#app.route('/showfilepath/<filename>')
def uploaded_file2(filename):
print (filename)
return app.config["UPLOAD_FOLDER"] + filename
if __name__ == '__main__':
app.run(debug = True)
# index.html
open file
# a.txt
hey there ...
I have problem with Flask upload in local machine code are working but when upload code to server using apache show error
IOError: [Errno 2] No such file or directory:
u'app/static/avatars/KHUON.S.png'
Code :
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = 'app/static/avatars'
app.config['MAX_CONTENT_LENGTH'] = 1 * 600 * 600
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/User/Profile', methods=['GET', 'POST'])
def upload_profile():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
else:
flash("File extension not allow.")
return redirect(url_for('upload_profile', upload='error'))
return render_template("profile.html")
Ok, in upload.py you could do something like
import os
absolute_path = os.path.abspath(UPLOAD_FOLDER+file_name)
os.path.abspath returns the absolute path from the given relative path.