uploading files for a website using flask - html

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>

Related

How to send a string from python to HTML element using Flask

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

Path file issue when uploading csv file via laravel form to database

I want to upload a csv file to my database via a laravel form. I can only insert file if the file is stored into public folder. How can I correctly set path with fopen function?
When submitting form, my code uses only the csv that already exists in public folder and not the csv I try to upload. Except from the csv I also pass some other data to my controller. How can I alter code to receive form file and not public folder stored file?
1) Below is my form excerpt. At the bottom lines I try to upload the file.
<body>
<form method='post' enctype="multipart/form-data" action="/hard">
{{csrf_field()}}
<section>
<br>
<legend><i><b> Complete Data Below</b></i></legend>
<br>
</section>
<section>
Choose program:
<select name="sc" id="xaos">
<optgroup label="postgraduates">
#foreach($transport as $y)
<option value="{{$y->object_id}}">{{$y->object_name}}</option>
#endforeach
</optgroup>
</select>
</section>
<br>
<section>
ID number:
<input name='am' type='number' min="1000000" max="1999999" required="" oninvalid="this.setCustomValidity('1000000 < Value < 1999999')">
</section>
<br>
<section>
Select Language:
<select name="language" id="lang">
<option value="GR"> Greek</option>
<option value="EN"> English</option>
</select>
</section>
<br>
<section>
<label for="upload-file">select csv file</label>
<input type="file" name="upload-file">
</div>
<input type='submit' name='upload' value="Submit!">
</section>
</form>
<br>
<br>
</body>
2) And below is my controller code excerpt which handles file imported.
public function job(Request $p)
{
$a1 = $p -> get('sc');
$a2 = $p -> get('am');
$a3 = $p -> get('language');
$f_rownum = 0;
if (($handle = fopen ( 'MOCK_DATA.csv', 'r' )) !== FALSE)
{
while ( ($data = fgetcsv ( $handle, 1000, ';' )) !== FALSE )
{
$ac1=$data[0];
$ac2=iconv("Windows-1253", "UTF-8", $data[1]);
$ac3=iconv("Windows-1253", "UTF-8", $data[2]);
$ac4=iconv("Windows-1253", "UTF-8", $data[3]);
$ac5=$data[4];
...............
According to Laravel documentation you can store your csv file into the storage like this:
public function storeFile(Request $request)
{
$path = $request->file('upload-file')->store('{directoryName}');
return $path;
}
The above code store your file in storage and returns tha path which you can save it into your DB.
For retrieving the file, you can use this code if you want to force user to download the file:
return Storage::download('{pathWhichYouSavedInDB}');
or you can retrieve the content of the file by using this code:
$contents = Storage::get('{pathWhichYouSavedInDB}');
[I add the extra response which I wrote in the comments]
fopen requires a full-path url of the stored file to be able to open it. So you can get the file url and then pass it to the fopen function like this:
$url = Storage::url('file.jpg');
Or you can not to use fopen at all and just use the $contents which you already retrieved with
$contents = Storage::get('{pathWhichYouSavedInDB}');

html forms download file django

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'})

KeyError: 'filename' while linking python and html using karrigell

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

How to save text input as a file in HTML and Django

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