Python, Django: getting full path from file - python

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

Related

Store the uploaded .txt file with newlines in a variable Django

I wanted to store the content of an uploaded .txt file (with newlines) in a variable, so that I could call my other functions on that variable. But I can not find a way to achieve this. I tried all the methods, but it doesn't work
Here is the simple code example:
Template
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="txt">
<button type="submit" name="encode">Encode</button>
</form>
View
from .algorithms.algo import encoder
def encoder(request):
context = {'encoded':''}
if request.method == 'POST':
text = request.FILES['txt'].read()
encoded = encoder(text)
context['encoded'] = encoded
return render(request, 'template.html', context)
Also, when I tried to output the file, it showed me some strange text instead of the actual content of the file.
Please admins don't close this question, I've surfed all over the internet, but didn't find the answer for my question
Or is there a way to get the value from `textarea`, and store it in a variable with newlines?
Try:
text.decode("utf-8")
or
encoded.decode("utf-8")
before contexting the value
You need to decode the content first because the data you are reading is in bytes. You can do this by changing:
text = request.FILES['txt'].read() to text = request.FILES['txt'].read().decode()
or you can decode it after with:
text = text.decode()

Django upload file using get method

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)

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>

Pyramid app: How can I pass values into my request.route_url?

I have this in my views.py file as the view config for my home page:
#view_config(route_name='home_page', renderer='templates/edit.pt')
def home_page(request):
if 'form.submitted' in request.params:
name= request.params['name']
body = request.params['body']
page=Page(name,body)
DBSession.add(page)
return HTTPFound(location=request.route_url('view_page',pagename=name))
return {}
Also, here is the form in the edit.pt template:
<form action="/view_page" method="post">
<div>
<input type="text" name="name"/>
</div>
<div>
<input type="text" name="body"/>
</div>
<label for="stl">Stl</label>
<input name="stl" type="file" value="" />
<input type="submit" name='form.submitted' value="Save"/>
</form>
Also in my init.py file I have
config.add_route('home_page', '/')
config.add_route('view_page', '/{pagename}')
right now when I submit the form it just tries to go to localhost:6543/view_page. This returns a 404 as there is no view_page resource or route leading to it. Instead I want it to go to localhost:6543/(the name of the page I just created aka the first input box in the form). How can I do this?
Edit: I am worried that something else may be telling it to route to view_page because I even tried changing it to
return HTTPFound(location=request.route_url('front_page',pagename=name))
And it still goes to /view_page. There is no route named front_page, so I would at least suspect it to throw an error.
Also, I would really appreciate it if you could tell me where you found the info. I have been looking at http://docs.pylonsproject.org/projects/pyramid/en/1.4-branch/api/request.html?highlight=request.route_url#pyramid.request.Request.route_url but can't seem to find use from it.
Edit: should I be using an asset specification instead of a path name? so
return HTTPFound(Location=request.route_url('tutorial:templates/view.pt','/{pagename}'))
Also, I am working through this article which seems very helpful with the syntax: http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html#urldispatch-chapter
I think your form should submit to "/", ie.
<!-- where your home_page route is waiting for the POST -->
<form action="/" method="post">
With the prior answers this now looks correct:
return HTTPFound(location=request.route_url('view_page', pagename=name))
My first guess is that it's location not Location as the argument to HTTPFound.
from the link you give
it's should be
return HTTPFound(location=request.route_url('view_page',pagename=name))
when you had add this route
config.add_route('view_page', '/{pagename}')
and set the variable name before
name= request.params['name']

Python file upload "KeyError"

Whats wrong in this code?
Here is my HTML:
<html><body>
<form action="iindex.py" method="POST" enctype="multipart/form-data">
<p>File: <input type="file" name="ssfilename"></p>
<p><input type="submit" value="Upload" name="submit"></p>
</form>
</body></html>
This is my Python script:
#! /usr/bin/env python
import os, sys;
from mod_python import apache
import cgi
import cgitb; cgitb.enable()
form = cgi.FieldStorage(keep_blank_values=1)
fileitem = form["ssfilename"]
.....
This is the line where I get KeyError.
File "/Applications/MAMP/python/framework/Python.framework/Versions/2.6/lib/python2.6/cgi.py", line 541, in __getitem__
raise KeyError, key
KeyError: 'ssfilename'
Edit: Totally missed the part where you are doing keep_blank_values = 1; sorry, no idea what is wrong.
From http://docs.python.org/library/cgi.html:
Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep_blank_values keyword parameter when creating the FieldStorage instance.
Therefore, this is happening because this field was left blank.
I had the exact same problem, make sure you have the "enctype" set to "multipart/form-data" and use a default value in your field. So your form should look like this:
<form enctype="multipart/form-data" id="addFile" action="AddFile.py">
<input type="file" name="file" id="file" value=""/><br/>
<input type="submit" name="submit" value="Add File"/><br/>
</form>
I was also using a JQuery handler for my Form and was trying to serialize it and then posting it to my python handler, I bypassed that and it was going all fine, so you should try that also.
Check if you have no GET parameters in your form action URL.
If you need to pass on any data put it as form elements inside the form to be POSTed along with your upload file.
Then you find all your POSTed vars in cgi.FieldStorage.

Categories

Resources