I am trying to read a file in using python/Flask and display it at the click of a button. To view the file, a return function like this works fine:
return redirect(url_for('uploaded_file',filename=filename))
But I am trying to implement in HTML to view file at a click. Something like this:
<form><input action="redirect(url_for etc. ??)" type=submit value=viewFile> </form>
What would be the correct syntax for action?
Thanks for any hint.
The action attribute should go on <form>, not <input>. The value of action should just be the URL of your route which accepts the file. Assuming you're using Jinja2, something like this:
Jinja2:
<form action="{{url_for('upload')}}" enctype="multipart/form-data">
<input type="file" name="view_file">
<input type="submit" value="Upload">
</form>
Python:
#app.route('/upload', methods=['POST'])
def upload():
# Handle upload and save to disk here..
return redirect(url_for('uploaded_file', filename=filename))
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
See also http://flask.pocoo.org/docs/0.11/patterns/fileuploads/ (it looks like you are already working from that example..)
This code worked for me to pass filename to html form input.
python:
...
return render_template('view.html', cat = filename)
html (view.html):
<!doctype html>
<form action="{{url_for('uploaded_file', filename=cat)}}" enctype="multipart/form-data">
<input type=submit value='view file'>
</form>
Related
Taking a folder(more than 15000 files) input using html file type and handling that via python post request for a large file, it is showing error.
<form action="{{url_for('home')}}" method="post" enctype="multipart/form-data">
<p>Select directory: </p>
<input type="file" webkitdirectory="" mozdirectory="" name="files" />
</form>
In python using Flask:
#app.route('/', methods=['GET','POST'])
def home():
if request.method =="POST":
return "ok"
Good evening,
I'm trying to select a file ("example.csv") via a input inside my template:
main.html
...
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myFile">
<button class="btn btn-success" type="submit">Choose</button>
</form>
...
After selecting and hitting the button I want to achieve the full path plus the name of the file itself as a string!
views.py
...
if request.method == 'POST' and request.FILES['myFile']:
myFile = request.FILES['myFile']
file_path = # getting the full file path
...
For example:
data_name = 'example.csv'
file_path = 'C:\Users\John Doe\Files'
So the string should look something like this: 'C:\Users\John Doe\Files\example.csv'
I tried it with os.path, but this doesn't seem to work or I'm doing something wrong here!?
Thanks for all your help!
It's not possible to get the user's local path of the file, the browser doesn't give such information. Usually the information you get is the Size, Type, Filename.
Check This, This and This
I would like to upload a single file or files at a time using get method.
I have already done with the post method and working fine. But for some reason i would like to do the file upload using get method using command line.
The below code is which i have already tried to get the string from get method and i can able to get the varValue as string. But i would like to get the file using get method.
def home(request):
if request.method == 'GET':
varValue = request.GET.get('myfile', '')
print(varValue)`
HTML code:
<form method="GET" enctype="multipart/form-data">
<input type="file" name="myfile" accept="image/*" multiple>
<button type="submit">Upload files</button>
Try This Method
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
A dictionary-like object containing all uploaded files. Each key in FILES is the name from the . Each value in FILES is an UploadedFile.
<form method="GET" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload File</button>
</form>
Found the solution using the post method itself. By skipping the csrf token we can do the command line script execution method.
Python views.py code below
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def home(request):
if request.method == 'POST':
uploaded_file = request.FILES['myfile']
fs = FileSystemStorage()
name = fs.save(uploaded_file.name, uploaded_file)
print(name)
return render(request, "home.html")
HTML code:
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="myfile" accept="image/*" multiple>
<button type="submit">Upload files</button>
</body>
python code for file upload using post method:
import requests
files = {'myfile': open('d:\\20190819-140341-627485.png','rb')}
y = requests.post("http://127.0.0.1:8000",files=files)
I have a little script that is an image scraper. Essentially, you provide the script with a link and it downloads all the images on the webpage to a folder on your desktop. I would like the same functionality but on the browser. I ant users to enter a link and the script starts downloading the images from the link to their computer. My Code Is Below:
#app.route('/')
def main():
return render_template('index.html')
#app.route('/Downlading', methods=['POST'])
def Downlading():
url= request.form['url']
start = request.form['start']
end = request.form['end']
dphy = image_downloader(url) #this is the script that saves the images
return str(dphy)
I am able to get the user url and pass it to image_downloader, which downloads the images. The problem is that the images get downloaded from the command prompt. I want the script to run inside the browser, just like it would run in my IDE. Sorry if this is confusing.
My HTML code:
<form action="/Downlading" method="POST" >
URL: <input type="text" name="url"><br/>
Start: <input type="text" name="start"><br/>
End: <input type="text" name="end"><br/>
<input type="submit" name="form" value="Submit" />
</form>
You need to create an HTML template for the variable to be reflected on. For example:
HTML - upload.html:
<html>
<title>Example on StackOverflow</title>
<p> The str representation of the variable dphy is {{ dphy }} </p>
</html>
Python (add this to existing flask script):
#app.route('/Downlading', methods=['POST'])
def Downlading():
url= request.form['url']
start = request.form['start']
end = request.form['end']
dphy = image_downloader(url) #this is the script that saves the images
return render_template('upload.html', dphy=str(dphy))
This should work, but I can't test it right now so I'm not positive. This is the basic idea for passing variables through Flask - create a template that uses the variable, then pass it in explicitly when rendering that created template.
I´m building a little web application using python 2.7 and flask (my first one).
I´m trying to include three HTML forms in one flask view to have all three of the forms on one webpage:
One form to allow data upload (will be an XML-file)
One Button to start a python process, that performs analysis on the XML-file
One Button that allows download of the results of step 2
While I got it working, when using a separate view for each of the three steps, I somehow can´t get it done when trying to include all three steps in one view. Does anyone know what I am doing wrong?
Here´s my code so far. The HTML-code is included in the python script. Working with templates didn´t help me either. The HTML page is working, but the buttons don´t perform any action.
...
#app.route('/PAM', methods=['GET', 'POST'])
def start_PAM():
if request.method == 'POST':
if "Upload" in request.form.values():
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))
print "File upload complete !!"
return redirect('/PAM')
elif "Start PAM" in request.form.values():
import os
os.system("D:\Python_Test\PAM\PAM_1st_Try.py")
print "PAM Process Finished!!"
return redirect('/PAM')
elif "Download" in request.form.values():
filename = "FILE.XML"
return redirect(url_for('download_file', filename=filename))
return '''
<!doctype html>
<title>Start PAM Process</title>
<h1>XML Upload</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<p><h1>Start the PAM Process</h1>
<form name='Start PAM' method='POST'>
<p><input type="submit" value="PAM" class="submitButton"/>
</form>
<p><h1>Download Result</h1>
<form name='Download' method='POST'>
<p><input type="submit" value="Download" class="submitButton"/>
</form>
'''
#app.route("/downloads/<filename>")
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
app.debug = True
if __name__ == '__main__':
app.run()
I think the step you're missing is to assign an action to the forms. At the moment the HTML doesn't know what to do with the form?
http://www.w3schools.com/tags/att_form_action.asp