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.
Related
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.
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))
This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Safely create a file if and only if it does not exist with Python
(3 answers)
Closed 4 years ago.
I want, before uploading a file in image folder, to check if the file in the folder already exists or not. If the file already exists it should show a message.
from flask import Flask, render_template, request
from werkzeug import secure_filename
UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'GIF'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
import os, os.path
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLD = '/python/image/'
UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_FOLD)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route('/upload')
def load_file():
return render_template('upload.html')
#app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug = True)
You can check whether a path exists or not by using os.path.exists method, it returns True if the path passed as a parameter exists and returns False if it doesn't.
For instance: If you want to check if there is any file named hello.c in the current working directory, then you can use the following code:
from os import path
path.exists('hello.c') # This will return True if hello.c exists and will return False if it doesn't
Or You can use the absolute path too
For instance: If you want to check if there is any folder named Users in your C drive then you can use the following code:
from os import path
path.exists('C:\Users') # This will return True if Users exists in C drive and will return False if it doesn't
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