Django upload file using get method - python

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)

Related

Use flask to get an image uploaded on a html form

I am new to flask and i am using google colab to do some basic flask stuff.
I have a html-form:
<!DOCTYPE html>
<html>
<body>
<h1>The input accept attribute</h1>
<form action="#" method="post">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" enctype="multipart/form-data" accept="image/*">
<input type="submit" value="submit">
</form>
</body>
</html>
Then i have FLASK code as to get the uploaded image:
#app.route("/test", methods=['POST','GET'])
def test_page():
if request.method == "POST":
image = request.files.get('img', '')
image = request.form["img"]
print("img ",image)
return "<h1> yo! </h1>"
else:
return render_template('index.html')
DEBUGGING RESULTS:
#debug
print('request.method', request.method)
print('request.args', request.args)
print('request.form', request.form)
print('request.files', request.files)
request.method POST
request.args ImmutableMultiDict([])
request.form ImmutableMultiDict([('img', 'cat.jpg')])
request.files ImmutableMultiDict([])
The problem is i want to doo some processing on the uploaded image but request.files return nothing and request.form just gives me the name. Please any help will be appreciated.
The enctype attribute should be defined within the form tag, not within the input element. Here, the formatting of the data is defined when the form is transmitted.
This could fix the problem.
<form method="post" enctype="multipart/form-data">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" accept="image/*">
<input type="submit" value="submit">
</form>

How to save an image into a folder inside the static folder using HTML form input type file and flask

In my flask app I want the user to be able to upload an image to a folder inside the static folder - called wallpaper. Currently I'm receiving a flask.debughelpers.DebugFilesKeyError, however I don't see any error in the keys I'm using
What I've tried
flaskapp.py
#app.route('/changeWallpaper' , methods = ['POST', 'GET'])
def change_home_wallpaper():
UPLOADS_PATH = join(dirname(realpath(__file__)), 'static\\wallpaper')
if request.method == "POST":
wallpaper = request.files['wallpaper']
if wallpaper.filename != '':
image = request.files['wallpaper']
image.save(os.path.join(UPLOADS_PATH, secure_filename(image.filename)))
cur = db2.cursor()
sql = f"UPDATE wallpaper set pic = {wallpaper.filename} where sno = 1"
cur.execute(sql)
db2.commit()
cur.close()
return redirect(url_for('home'))
else:
return redirect(url_for('home'))
loggedin.html
<div class="jumbotron">
<form action="{{url_for('change_home_wallpaper')}}" method="post">
<div class="container">
<input type="file" name="wallpaper"/>
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
Update your HTML
<form action="/path" method="post" enctype="multipart/form-data">
</form>
and put {wallpaper.filename} in quotes.

flask html input format

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>

Processing POST request in Django

Hi I got a simple form for a POST request and it works when I'm only having one input, but not two inputs together. Can someone show me some light on this?
index.html
<form name="input" action="{% url 'sending' %}" method="post">
{% csrf_token %}
Recipient: <input type="text" name="recipient">
<br>
Message: <input type="text" name="content">
<br>
<input type="submit">
</form>
views.py
def sending(request):
recipient = request.POST.get('recipient','')
content = request.POST.get('content','') #not working when I am doing this...
someMethod(recipient, content)
return HttpResponseRedirect(reverse('results'))
Adding a "forms" portion to your setup will help you greatly... see the quickstart docs on forms here: https://docs.djangoproject.com/en/1.6/topics/forms/
In particular, check out "using a form in a view": https://docs.djangoproject.com/en/1.6/topics/forms/#using-a-form-in-a-view
Basically, you end up with a "forms.py" file which defines your form fields. Then, after it all processes, you get a simplier API into your form fields that looks like this:
form.cleaned_data['recipient']
form.cleaned_data['content']
etc.

flask - url with searched word

I want to ask how to make my urls to include the worh that I searched. Something like this:
http://host/filter?test
My code:
#app.route('/filter', methods=['POST', 'GET'])
def filter():
if request.method == 'POST':
if str(request.form['search_string']) <> '':
api.queryMessage(request.form['search_string'])
return render_template('main.html', search_string=search_string)
And my template, main.html:
<form name="filters" action="{{ url_for('filter') }}" method=post id="filters">
<div style="position: absolute; top:100px; left:300px">
<p>Search string: <input type=text size=80 title="Match all of the words" name=search_string value="{{search_string}}"></p>
<input type=submit value=Filter/Search onclick=loopSelected();>
<input type="hidden" name="chosen" id="chosen" value="{{chosen}}" />
</div>
</form>
You're now using POST request. Use GET request, so browser will put your form values to URL.
in HTML form set method="GET":
<form name="filters" action="{{ url_for('filter') }}" method="GET" id="filters">
You'll get URL in the following form:
http://host/filter?search_string=test&chosen=<id>&<some other trash>
In Flask use request.args instead of request.form:
if request.method == 'GET':
if request.args.get('search_string'):
...

Categories

Resources