Flask renaming uploaded file - python

in my app i am uploading images to a folder but i cannot figure out how to rename them from the form to something
this is my .py
import os
from flask import Flask, render_template, request
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route("/")
def index():
return render_template("upload.html")
#app.route("/upload", methods=['GET','POST'])
def upload():
target = os.path.join(APP_ROOT, 'images/')
print(target)
if not os.path.isdir(target):
os.mkdir(target)
for file in request.files.getlist("file"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("complete.html")
if __name__ == "__main__":
app.run(port=4555, debug=True)
this is my .html
obviously the input type="text" isn't working for me
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Upload here</h1>
<form id="upload-form" action="{{url_for('upload')}}" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*" multiple></br>
New name for image<input type="text">
<input type="submit" value="send">
</form>
</body>
</html>

for file in request.files.getlist("file"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
Here you set the destination for the file which includes the new filename. You set filename to file.filename - essentially you are saying to keep the filename.
To rename the file you can overwrite the filename like so:
filename = "myfile.jpg"
This could be dynamic, eg:
# keep extension for later
extension = filename.split()[-1]
current_dt = datetime.datetime(
new_filename = "upload-{}.{}".format(
time.time(), extension
)
This would save the file as something like: 1574685161.690482.jpg

Related

Flask / Python: Modify uploaded file data before saving

I would like to be able to upload a csv file, then have a script in python do some modifications to the file, and finally save the file after changes to a specific folder. I have something like this, but I don't know why it doesn't work:
import os
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
app = Flask(__name__)
UPLOAD_FOLDER = 'C:/Users/tkp/Desktop/uploads_files'
app.config['UPLOAD_EXTENSIONS'] = ['.csv']
app.config['UPLOAD_PATH'] = UPLOAD_FOLDER
#app.route('/')
def index():
files = os.listdir(app.config['UPLOAD_PATH'])
return render_template('index.html', files=files)
#app.route('/', methods=['POST'])
def upload_files():
uploaded_file = request.files['file']
filename = secure_filename(uploaded_file.filename)
if filename != '':
uploaded_file.stream.seek(0)
f = uploaded_file.read()
#some change in the file
f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
return redirect(url_for('index'))
#app.route('/Users/tkp/Desktop/uploads_files/<filename>')
def upload(filename):
return send_from_directory(app.config['UPLOAD_PATH'], filename)
And HTML file:
<!doctype html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Convert"></p>
</form>
<hr>
</body>
</html>
Is it possible to perform such an operation on the fly or do you have to save the uploaded file first?
You are doing everything correctly, except the f.save(...) definition.
When you do f = uploaded_file.read(), the f is the result of the .read() operation, which is bytes, not a file.
You have to open another file and save the contents to it.
Don't forget to .decode() the bytes, to make it a string.
Here's a working snippet:
#app.route('/', methods=['POST'])
def upload_files():
uploaded_file = request.files['file']
filename = secure_filename(uploaded_file.filename)
if filename != '':
uploaded_file.stream.seek(0)
f = uploaded_file.read().decode()
# WE don't want any failures
f = f.replace("FAIL", "SUCCESS")
filename_to_save = os.path.join(app.config['UPLOAD_PATH'], filename)
with open(filename_to_save, "w") as file_to_save:
file_to_save.write(f)
return {"status": "OK"}
It could probably be a typo in your action attribute. Change this line:
<form method="POST" action="" enctype="multipart/form-data">
to this:
<form method="POST" action="/" enctype="multipart/form-data">

How to read single file in my data using Flask

I'm new in Flask, I want to take single file that have been uploaded in my upload path. Then i want to read and send it to my html after hr tag. How can i do that?
This is My Code:
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
send_from_directory
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_EXTENSIONS'] = ['.txt', '.doc']
app.config['UPLOAD_PATH'] = 'uploads'
#app.route('/')
def home():
files = os.listdir(app.config['UPLOAD_PATH'])
return render_template('home.html', content=files)
#app.route('/', methods=['POST'])
def upload_file():
uploaded_file = request.files['file']
filename = secure_filename(uploaded_file.filename)
if filename != '':
file_ext = os.path.splitext(filename)[1]
if file_ext not in app.config['UPLOAD_EXTENSIONS']:
abort(400)
uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
return redirect(url_for('home'))
if __name__ == "__main__":
app.run()
And This one is my HTML Page:
<!doctype html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
<hr>
{{ content }}
</body>
</html>
It saves the data, but I can't access the data since I use this codefiles = os.listdir(app.config['UPLOAD_PATH'])
You need a variable route that will accept the a filename like #app.route('/<filename:filename>').
You then need to get the file with that name from your upload directory like file_path = os.path.join('UPLOAD_PATH', filename).
Then you need to read the contents of that file and pass it into your view.
with open(file_path) as file:
content = file.read()
Then you can access it in your HTML file and display it.
<p>{{ content }}</p>
Here is a complete example of the route I described:
#app.route('/<filename:filename>')
def display_file(filename):
file_path = os.path.join('UPLOAD_PATH', filename)
with open(file_path) as file:
content = file.read()
return render_template('display_file.html', content=content)

Jinja2 Using images in HTML

I wasted a lot of time to find out what is wrong. I need your help now.
I want to render template with image from my filesystem. But it is not working.
Path - string that contains file name
#app.route('/', methods=['GET'])
def main():
return render_template('main.html',image = path)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h2></h2>
<form method="post" enctype="multipart/form-data" action="/uploader">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
<img src={{ url_for('static', filename = image) }} >//i can't figure how to change this to use {{image}}
</body>
</html>
Just generate full image path in your view and pass it to your template
#app.route('/', methods=['GET'])
def main():
#path is filename string
image_file = url_for('static', filename=path)
return render_template('main.html', image_file=image_file)
and then just use it as full link
<img src={{ image_file}} >
if you have image file (with filename which stored in path) in your static folder this should work
If you was set the static folder like that (or other methods):
from flask import Flask
app = Flask(__name__, static_folder='static')
#app.route('/', methods=['GET'])
def main():
return render_template('main.html', image = url_for("static", filename=path))
or shorter:
return render_template('main.html', image='/static/' + path))
after you will put your image in /static folder you can get it from template:
<img src="{{image)}}">
I think something like this should work.
<img src="{{ url_for('static', filename='image') }}">
Where 'image' refers to the path of the image file inside static folder. Make sure to use the full name of image file along with its file type i.e. jpg, png etc.

Flask Upload File Not Found

I want to make a file uploader using Python, Flask, and HTML. If I upload a file I get:
Not Found
The requested URL was not found on the server. If you entered the URL
manually please check your spelling and try again.
import os
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = './user/Tom/Files/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
#app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == ['POST']:
if 'file' not in request.files:
flash('Geen Bestand')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('Geen Bestand')
return redirect(request.url)
if not os.path.exists("user/Tom/Files/"):
os.makedirs("user/Tom/Files/")
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('uploaded_file',
filename=filename))
return render_template("index.html")
if __name__ == ('__main__'):
app.run(debug=True, port=8000)
<!DOCTYPE html>
<html>
<head>
<title>Upload a File!</title>
</head>
<body>
<form method="post" action="user/Tom/Files/" enctype="multipart/form-data">
<input type="file" id="customFile" name="file">
<input type="submit" name="Upload" value="Upload">
</form>
</form>
</body>
</html>
I deleted the action and the value
Now i have this:
<form method="post" enctype="multipart/form-data">
<input type="file" id="customFile" name="file">
<input type="submit" name="Upload">
</form>
But now it stay on de index.html but doesnt upload it to /user/Tom/Files/ ?

Files not uploading in flask

I am trying to upload files into server using flask but the files are *not uploading.
I am new to python and flask.
import os
from flask import *
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route('/')
def index():
return render_template('upload.html')
#app.route('/upload', methods = ['POST'])
def upload():
target = os.path.join(APP_ROOT, 'uploads/')
if not os.path.join(target):
os.mkdir(target)
for file in request.files.getlist('file'):
print(file.filename)
destination = '/'.join([target, file.filename])
print(destination)
file.save(destination)
return render_template('successful.html')
if __name__ == '__main__':
app.run(debug = True)
upload.html
<!DOCTYPE html>
<html>
<head>
<title> Upload file </title>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}"
method="post" enctype="multipart/form-data">
<input type="file" name="cssv_file" multiple>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Change this line
if not os.path.join(target):
to
if not os.path.isdir(target):

Categories