I wants to browse image & upload image to folder in my application using python
when i click on submit button its shows me http://www.domain.com/store_mp3_view & image is not uploaded
html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="/store_mp3_view" method="post" accept-charset="utf-8"
enctype="multipart/form-data">
<label for="mp3">Mp3</label>
<input id="mp3" name="mp3" type="file" value="" />
<input type="submit" value="submit" />
</form>
</body>
</html>
python file code
import os
import uuid
from pyramid.response import Response
def store_mp3_view(request):
# filename contains the name of the file in string format.
#
# WARNING: this example does not deal with the fact that IE sends an
# absolute file path as the filename. This example is naive; it
# trusts user input.
filename = request.POST['mp3'].filename
# ``input_file`` contains the actual file data which needs to be
# stored somewhere.
input_file = request.POST['mp3'].file
# Note that we are generating our own filename instead of trusting
# the incoming filename since that might result in insecure paths.
# Please note that in a real application you would not use /tmp,
# and if you write to an untrusted location you will need to do
# some extra work to prevent symlink attacks.
file_path = os.path.join(/files, '%s.mp3' % uuid.uuid4())
# We first write to a temporary file to prevent incomplete files from
# being used.
temp_file_path = file_path + '~'
output_file = open(temp_file_path, 'wb')
# Finally write the data to a temporary file
input_file.seek(0)
while True:
data = input_file.read(2<<16)
if not data:
break
output_file.write(data)
# If your data is really critical you may want to force it to disk first
# using output_file.flush(); os.fsync(output_file.fileno())
output_file.close()
# Now that we know the file has been fully saved to disk move it into place.
os.rename(temp_file_path, file_path)
return Response('OK')
return Response('OK')
You can use models filefield inside models.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents/', max_length=5234,blank=True, null=True,)
corresponding forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(label='', show_hidden_initial='none',required=True,)
Inside views.py
if request.FILES.has_key('your_fileName'):
newdoc = Document(docfile = request.FILES['your_fileName'])
newdoc.save()
I got it working with above code, hope it helps
With this code you can upload multiple files
def insert_file(self):
for i in request.FILES.getlist('mp3'):
fileName = i.name
out_file = open(fileName,'w')
out_file.write(i.read())
return HttpResponse('Inserted Successfully')
Related
I am creating a tool where either
A new XLSX file is generated for the user to download
The user can upload an XLSX file they have, I will read the contents of that file, aand use them to generate a new file for the user to download.
I would like to make use of Pandas to read the XLSX file into a dataframe, so I can work with it easily. However, I can't get it working. Can you help me?
Example extract from CGI file:
import pandas as pd
import cgi
from mako.template import Template
from mako.lookup import TemplateLookup
import http.cookies as Cookie
import os
import tempfile
import shutil
import sys
cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))
method = os.environ.get("REQUEST_METHOD", "GET")
templates = TemplateLookup(directories = ['templates'], output_encoding='utf-8')
if method == "GET": # This is for getting the page
template = templates.get_template("my.html")
sys.stdout.flush()
sys.stdout.buffer.write(b"Content-Type: text/html\n\n")
sys.stdout.buffer.write(
template.render())
if method == "POST":
form = cgi.FieldStorage()
print("Content-Type: application/vnd.ms-excel")
print("Content-Disposition: attachment; filename=NewFile.xlsx\n")
output_path = "/tmp/" + next(tempfile._get_candidate_names()) + '.xlsx'
data = *some pandas dataframe previously created*
if "editfile" in form:
myfilename = form['myfile'].filename
with open(myfilename, 'wb') as f:
f.write(form['myfile'].file.read())
data = pd.read_excel(myfilename)
data.to_excel(output_path)
with open(path, "rb") as f:
sys.stdout.flush()
shutil.copyfileobj(f, sys.stdout.buffer)
Example extract from HTML file:
<p>Press the button below to generate a new version of the xlsx file</p>
<form method=post>
<p><input type=submit value='Generate new version of file' name='newfile'>
<div class="wrapper">
</div>
</form>
<br>
<p>Or upload a file.</p>
<p>In this case, a new file will be created using the contents of this file.</p>
<form method="post" enctype="multipart/form-data">
<input id="fileupload" name="myfile" type="file" />
<input value="Upload and create new file" name='editfile' type="submit" />
</form>
This works without the if "editfile" in form: bit so I know something is going wrong when I am trying to access the file that the user has uploaded.
The problem is that whilst a file is created, the created file has a file size of 0 KB and will not open in Excel. Crucially, the file that the user has uploaded can not be found in the location that I have written it out.
You've passed myfilename to pandas; however that file doesn't exist on the server yet. You'll have to save the file somewhere locally first before using it.
The following will download the file to the current directory (same directory as the CGI script). Of course, you're welcome to save it to some more suitable directory, depending on your setup.
form = cgi.FieldStorage()
myfilename = form['myfile'].filename
with open(myfilename, 'wb') as f: # Save the file locally
f.write(form['myfile'].file.read())
data = pd.read_excel(myfilename)
I have a basic flask website and I would like to know how to write the input from a basic input box into a csv or txt file. I thought my code would work but all it did was create a blank csv file.
My code:
from flask import Flask, request, render_template
import csv
import io
app = Flask(__name__)
f = open('test.csv')
outFile = open('containers.csv', 'w')
free = csv.reader(f)
outFile.write("number" + '\n')
#app.route('/')
def my_form():
return render_template('form.html')
#app.route('/', methods=['POST'])
def my_form_post():
text = request.form['u']
marker = str(text)
return "You inputed " + text
for row in free
outFile.write(marker + '\n')
f.close()
outFile.close()
if __name__ == "__main__":
app.run()
My html code is:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Input</title>
</head>
<body>
<form method="POST">
<p>Input</p><br>
<input name='u'>
<input type='submit'>
</form>
</body>
</html>
I'm pretty sure the problem is in the python section but I don't know what's going wrong
To write to a text file, why not define a function like:
def write_file(data):
with open('containers.txt', 'a') as f:
f.write(data + '\n')
Putting the open function within the with statement, means the f object is available within that block. The file is also automatically closed when the block finishes.
Then you could have a single view function which handles both rendering the form, and accepting the posted result:
#app.route('/', methods = ['GET','POST'])
def my_form():
if request.method=='POST':
text = request.form['u']
write_file(text)
return "You inputed " + text
elif request.method=="GET":
return render_template('form.html')
You should also add an action attribute to the form start tag:
<form method='POST' action='{{ url_for("my_form") }}'>
Now the form will submit to the correct endpoint, even if you change the endpoint which is assigned to the my_form function.
When I try to Upload an image file to the '\tmp\' directory via my python cgi script below,
#!c:/Python/python.exe -u
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,)
It gives me this error:
<type 'exceptions.IOError'>: [Errno 2] No such file or directory: '/tmp/(_)Mr#_--Soft_3Ovo(_)?.jpg'
args = (2, 'No such file or directory')
errno = 2
filename = '/tmp/(_)Mr#_--Soft_3Ovo(_)?.jpg'
message = ''
strerror = 'No such file or directory
'
Below is my HTML Code for selecting a file to upload, I am certain there is no error but i dont know why its not working.:
<html>
<body>
<form enctype="multipart/form-data" action="save_file.py" method="post">
<p>File: <input type="file" name="filename" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
You should sanitize your filename. Do not trust on user input for that.
You should read the directory traversal section of http://www.djangobook.com/en/2.0/chapter20.html ,and maybe also the other parts.
So i am following the web.py uploading and storing guide to test it out but i keep geting a
error stating that [Errno 2] No such file or directory :< help
this is my code
import web
urls = (
'/hello', 'index',
'/hello/upload', 'upload'
)
app = web.application(urls, globals()) # handels http request that aks for urls
# the base ells lpthw.web to use the templates/layout.html file as the base template for all the other templates
render = web.template.render('templates/', base="layout")
# must use port 127.0.0.1:5000
class index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="Nobody", greet="Hello")
greeting = "%s, %s" % (form.greet, form.name)
return render.index(greeting = greeting)
class upload(object):
def POST(self):
x = web.input(files={})
filedir = '/project/webtest/templates' # directory were you want to save the file
if 'files' in x: # check if the file -object is created
filepath=x.files.filename.replace('\\','/') # replace the windows -style slashes with linux ones
filename=filepath.split('/')[-1] #splits the and chooses the last part (the filename with extension
fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
fout.write(x.files.file.read()) #writes the uploaded file to the newly created file.
fout.close() #closes the file
else:
return "Error no file"
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
help thx
import web
urls = ('/upload', 'Upload')
class Upload:
def GET(self):
web.header("Content-Type","text/html; charset=utf-8")
return view.upload()
def POST(self):
x = web.input(myfile={})
filedir = '/path/where/you/want/to/save' # change this to the directory you want to store the file in.
if 'myfile' in x: # to check if the file-object is created
filepath=x.myfile.filename.replace('\\','/')
filename=filepath.split('/')[-1]
fout = open(filedir +'/'+ filename,'w')
fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
fout.close() # closes the file, upload complete.
raise web.seeother('/upload')
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
upload.html
<html>
<head>
<title>File upload</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" /><br/>
<input type="submit" />
</form>
</body>
</html>
for your reference http://webpy.org/cookbook/storeupload/
I met the same problem myself, and tried to ask that here. But nobody answers.
Finally, I figured it out what's the problem and would like to share with you!
This part: filedir = '/project/webtest/templates' should be an absolute path.
And it should be an existing directory (at least in my trail it should be an existing directory, otherwise it would prompt the same error as you posted)! The file need not to be exciting since we are going to create it by copying the uploaded file.
For example in my mac, it's '/Users/J/pythonex/projects/gothonweb/docs', and it's an existing directory. If it's not an existing directory, you will get the same error message.
Last, the most tricky part. Im my mac, the uploaded files are actually stored in my disk in that exact directory. But I can't see them in my finder until I relaunch the finder. I don't know why is that. But for my computer, that's the case.
I am using web.py and creating a basic webpage,
I had a basic html code which has a button as below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Home</title>
</head>
<body>
<form method="POST" action="/retrieve">
<button id="submit" name="submit">Retrieve</button>
</form>
</body>
So by the above code i can able to see a button on a page, when we click on the button Retrieve the action attribute activates and goes to required path to perform operation
index.py code
import web
import csv
urls = (
'/retrieve', 'Retrieve',
)
app = web.application(urls, globals())
conn = mdb.connect(user='root', passwd='redhat', db='Merion_dev', host='localhost')
class Retrieve:
def POST(self):
cursor = conn.cursor()
query = "SELECT * FROM adm_facility LIMIT 0,10 "
cursor.execute(query)
result = cursor.fetchall()
csv_file = csv.writer(open('Test_File.csv', 'wb'))
csv_file.writerow(['Facility_id', 'Name', 'Account Number', 'Street'])
for i in result :
csv_file.writerow([i[0],i[2],i[3],i[4]])
raise web.seeother('/retrieve')
if __name__ == "__main__":
web.internalerror = web.debugerror
app.run()
So when i run the above code , a csv file is successfully created with data from database by the select query written.
Now what i want to do is, when we click on the retrieve button the data should be written in to csv file and should be downloaded like
In phpmyadmin when we click on export button a file will be downloaded in different formats according to our selection, so but here i wan t to download a file(csv) after saving data in to it.
Can anyone please let me know
How can we download the csv file after saving data in to it by the above code
How can we download the csv file using python in general ?
You don't have to write it to a file, you could use StringIO for it:
from StringIO import StringIO
import csv
import web
urls = (
'/retrieve', 'Retrieve',
)
app = web.application(urls, globals())
conn = mdb.connect(user='root', passwd='redhat', db='Merion_dev', host='localhost')
class Retrieve:
def POST(self):
cursor = conn.cursor()
query = "SELECT * FROM adm_facility LIMIT 0,10 "
cursor.execute(query)
result = cursor.fetchall()
csv_file = StringIO()
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Facility_id', 'Name', 'Account Number', 'Street'])
for i in result :
csv_writer.writerow([i[0],i[2],i[3],i[4]])
web.header('Content-Type','text/csv')
web.header('Content-disposition', 'attachment; filename=yourfilename.csv')
return csv_file.getvalue()
if __name__ == "__main__":
web.internalerror = web.debugerror
app.run()