I'm trying to read an uploaded file using python 2.7 and Karrigell. But it is showing me:
Traceback (most recent call last):
File "C:\Karrigell-3.1.1\karrigell\core\HTTP.py", line 333, in process_request
File "C:\Karrigell-3.1.1\karrigell\core\k_target.py", line 399, in run
File "", line 7, in
File "cgi.pyc", line 541, in __getitem__
KeyError: 'filename'
Here is my web_access.py:
import cgi, os
form = cgi.FieldStorage()
fileitem=form['filename']
if fileitem.file:
print fileitem.file.read()
else:
print "Error"
My Html page:
<section>
Enter the text:
<form action="web_access.py" method="post" enctype="multipart/form-data">
<input type="file" name="filename" id="file" value="" size="50"/>
<br />
<input type="submit" value="Analyze"/>
</form>
</section>
Help me out please!
With Karrigell you don't need to use the CGI module ; you get a reference to form fields as keys of the built-in object REQUEST
web_access.py could be something like
print REQUEST['filename'].file.read()
This is documented here
Related
The files are getting uploaded in the azure blob as well as in the local folder where i write the code . Im trying to upload the files to azure blob and it is successful but the same files are getting uploaded in my coding folder .
I tired to upload the files to azure blob using flask for a website and it is done but the same files are getting uploaded in the local folder where my coding files exists.
I want to know why those files are getting uploaded in the local folder ,
this is my app.py code:
#app.route('/upload',methods=['POST'])
def upload():
if request.method == 'POST':
files = request.files.getlist('file')
for file in files:
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(filename)
blob_client = blob_service_client.get_blob_client(container = container, blob = filename)
with open(filename, "rb") as data:
try:
blob_client.upload_blob(data, overwrite=True)
msg = "Upload Done ! "
except:
pass
os.remove(filename)
return render_template("dashboard.html", msg=msg)
this is my html code:
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="input-field">
<p><center>Please fill in the details</center></p>
<input type="file" name="file" >
<div><label>Vidyavaradhi Service Agreement*</label><input type="file" name="file" ></div> --></div> <div><label>Passport copy*</label><input type="file" name="file"></div>
<div><label>Transcripts from university of graduation along with intermediate and tenth certificates*</label><input type="file" name="file" ></div>
<div><label>Letter of Recommendation statement of purpose*</label><input type="file" name="file"></div>
<div><label>Statement of purpose*</label><input type="file" name="file" ></div>
<div><label>Resume*</label><input type="file" name="file" ></div>
<div><label>Bank Statement*</label><input type="file" name="file" ></div>
How to send a sting text data from a python script to a specific HTML element. So that I can display it to users clearly and in a certain place using Flask Python library.
python script
#app.route('/services', methods=['POST', 'GET'])
def upload_image():
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No image selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
full_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(full_path)
# print('upload_image filename: ' + filename)
flash('Image successfully uploaded and displayed')
get_image(file.filename)
get_image_path()
data = 'render some text sting here'
print(data)
return render_template('services.html', filename=filename, dataToRender=data)
else:
flash('Allowed image types are -> png, jpg, jpeg, gif')
return redirect(request.url)
HTML
<form method="post" action="{{ url_for('upload_image') }}" enctype="multipart/form-data">
<label for="img" style="margin-bottom: 40px;font-size: 30px">choose image:</label>
<input type="file" onchange="preview(event)" autocomplete="off" required name="file"><br>
<img class="card-img-top" src="img/inttion.jpg" id="imgg" alt="Card image cap">
<p>
<input type="submit" value="Submit">
<h3>Your Recognition Result IS</h3>
<input type="text" name="result">
<h1>here is the result {{ dataToRender }}</h1>
</p>
</form>
To do what you are asking, you will have to make use of flask's ability to integrate with a templating engine (flask uses Jinja2 by default). This would look something like this:
In your main file with your routes in it, you will have to define a route on which you want to render a template
from flask import render_template
#app.route('/')
def index():
data = someFunction()
return render_template('index.html', dataToRender=data)
In another file called templates/index.html you will have to define the template and this is where you can dictate where the information that you provided will show up.
<!DOCTYPE html>
<title>Hello from Flask</title>
<h1>Hello {{ dataToRender }}!</h1>
I hope this helps. Flask also has some great documentation on the subject that can be found here
I am stuck with this issue in Django: I want to download a file already existing on my server through a html form. The file to be downloaded is served through a function in views. My problem is with html form and passing the file name to view. How can I pass the name of the file from form toward view without having to select the file?
In html I have:
# 'content' keeps the name of the file to be downloaded
{% block content %}
{{content}}
<table>
<tr>
<td>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<br />
<input type="submit" value="Download File" />
</form>
</td>
</tr>
</table>
{% endblock %}
When I select the file and press submit button, it works but I need a different behavior: the name of the file containing results (downloadable file) to be passed to views into a variable. The views will then serve it.
The view which handled the downloadable file:
def forecast(request):
if request.method == 'POST':
#handle_download_file(request.FILES['file'], str(request.FILES['file']))
print('request.method este: ',request.method)
RESULTS_filename = 'frcst_'+ str(request.FILES['file'])
#download('GET', RESULTS_filename)
file_path = os.path.join(os.path.relpath('forecast/'), RESULTS_filename)
print (file_path)
print(settings.MEDIA_ROOT)
with open(file_path,'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['content-disposition'] = 'attachment; filename='+RESULTS_filename
print(response)
return response
HttpResponseRedirect('/forecast/')
return render(request,'result_links.html',{'content':'frcst_history.csv'})
I am building a site where users can input text and submit the text so that it can be saved and accessed as a file on the server. Unfortunately, I am not quite sure how I would take the inputted text and save it aas a file.
Could anyone point me in the right direction as to how I might do this or detail the steps I will have to take? Preemptive apologizes if I have missed an obvious Google result. Being somewhat new to Django, I may have inadvertently glossed over helpful resources.
Here is the relevant HTML, mostly a form copied from a file upload form:
<form name="myWebForm" id="submissionCode_codeEditor" action="uploadFile/" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500" />
<input type="text" name="title" placeholder="File Name"/>
<input type="hidden" name="taskID" value={{ taskID }} />
<input type="submit" value="Submit This Code" />
</form>
Here is the relevant Django model:
class Upload(models.Model):
title = models.CharField(max_length=50)
fileUpload = models.FileField(upload_to='file_uploads')
userID = models.ForeignKey(User)
task = models.ForeignKey(Task)
uploadTime = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
You're looking for ContentFile. It's a Django File subclass that instantiates with a string of text instead of a literal file. You can then save the ContentFile to your FileField.
from django.core.files.base import ContentFile
content = ContentFile(some_text)
upload_instance.fileUpload.save('/path/to/where/file/should/save.txt', content)
upload_instance.save()
First of all create a file in your media folder using command, i am assuming user posted text with name content
from app.models import Upload
from django.conf import settings
content = request.GET("content")
file_object = open("%s/%s"%(settings.MEDIA_ROOT, filename),w) #Take file name as hash of content posted and username so that no class
upload = Upload(title=title, fileUpload=filename,user_id=request.user.id)
Your file is uploaded and can be acceseed using MEDIA_URL from settings
I want to retrieve the HTML form field data in a text file on my desktop.
I am having a HTML page containing the HTML form field box.
Further, I want to run a bash script taking the text file as a input.The bash script contains the command :
sed -f replacer input.txt > output.txt
I have to also include this output.txt file in another html form field.
Help me out.
Thank You.
Have html like this:
<form id="some" name="someName" method="post" action="/ur/url/to/post">
<input type="text" id="some1" class="someClass" value="" name="fileWrite"/>
<iput type="submit" value="submit" class="submitClass"/>
</form>
Have a php script like this:
$myFile = "testFile.txt";
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
$fileWrite = $_POST['fileWrite'];
}
if($fileWrite) {
$fh = fopen($myFile, 'a') or die("can't open file"); //Make sure you have permission
fwrite($fh, $fileWrite);
fclose($fh);
exec('/your/command /dev/null 2>/dev/null &');
}
Thats it. Job is done.