Hi so basically I have a form that uploads a file
<input class="btn btn-light" type="file" id="file" name="h" accept=".py">
I'm using bottle, so essentially I want to get the contents of the file but not have to save it locally. Using with open requires a path which I don't have as it is not saved locally.
f = request.POST['file']
I get the file using the above.
Is there any way I could upload the file without having to save it locally?
Any help would be much appreciated, I just need the name of the file and the contents.
No need to save the file (or to use BytesIO as suggested in a comment). You can simply read its contents:
from bottle import Bottle, request
app = Bottle()
#app.post("/upload")
def upload():
f = request.POST["file_name"]
text = f.file.read()
return f"Read {len(text)} bytes from the uploaded file.\n"
app.run()
Output:
$ echo "This is the file to upload." > file.txt
$ curl http://127.0.0.1:8080/upload -F file_name=#file.txt
Read 28 bytes from the uploaded file.
Related
I have one file stored in google drive which I download using:
url = 'https://docs.google.com/spreadsheets/d/ID/edit?usp=sharing'
output = 'file.xlsx'
gdown.download(url, output, quiet=False)
My goal is to make that file downloadable in a html file through a button using Google Drive as a backend. Is there any way to do that?
Summarizing:
Some user open an html file where there's a button to download some file placed in my drive.
the flask template I am thinking to use looks like:
from flask import Flask, Response
app = Flask(__name__)
#app.route("/")
def hello():
return '''
<html><body>
Hello. Click me.
</body></html>
'''
#app.route("/getPlotCSV")
def getPlotCSV():
# with open("outputs/Adjacency.csv") as fp:
# csv = fp.read()
excel = '1,2,3\n4,5,6\n'
return Response(
excel,
mimetype="xlsx",
headers={"Content-disposition":
"attachment; filename=file.xlsx"})
EDIT:
I mapped my html button with
"""<form action={url}> <input type=submit value=Go to Google/></form>"""
but it takes me directly to the spreadsheet in google sheets. How do I assign an action to that button so that the file is downloaded locally to the user?
I'm uploading multiple files to flask using a form, I'm getting the file objects in the flask backend without a problem but the issue is I want to read the PDF files to extract text from them. I can't do it on the file objects I received from the form, another method I thought of was saving the file in the local storage then read them again when I did that using file.save(path, filename) it created an empty text file with the name - filename.pdf
app=Flask(__name__)
#app.route('/')
def index():
return '''
<form method='POST' action='/saveData'>
<input type='file' name='testReport'>
<input type='submit'>
</form>
'''
#app.route('/saveData', methods=['POST'])
def saveData():
if 'testReport' in request.files:
testReport= request.files['testReport']
#This isn't working, a text file is saved with the same name ,ending in pdf
testReport.save(os.path.join(app.config['UPLOAD_FOLDER'], testReport.filename))
return f'<h1>File saved {testReport.filename}</h1>'
else:
return 'Not done'
How do we operate on PDF files after uploading them to flask ?
How do we operate on PDF files after uploading them to flask ?
You should treat them just like normal PDF files - if they were uploaded via Flask application or gathered using other method is irrelevant here. As you
want to read the PDF files to extract text from them.
you should use PDF text-extraction tool, for example pdfminer.six, as this is external module you need to install it first: pip install pdfminer.six
You can directly follow the flask own way as mentioned [here]
This easily works with pdfs. Just don't forget to include your extension in ALLOWED_EXTENSIONS
I have an HTML form (implemented in Flask) for uploading files. And I want to store the uploaded files directly to S3.
The relevant part of the Flask implementation is as follows:
#app.route('/',methods=['GET'])
def index():
return '<form method="post" action="/upload" enctype="multipart/form-data"><input type="file" name="file" /><button>Upload</button></form>'
I then use boto3 to upload the file to S3 as follows:
#app.route('/upload',methods = ['GET','POST'])
def upload_file():
if request.method =='POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
#file.save(os.path.join(UPLOAD_FOLDER,filename))
s3_resource = boto3.resource('s3',aws_access_key_id='****',
aws_secret_access_key='*****')
buck = s3_resource.Bucket('MY_BUCKET_NAME')
buck.Object(file.filename).put(Body=file.read())
return 'uploaded'
File is getting uploaded successfully in S3 Bucket. And when trying to open that file it is opening as blank text file. Even I tried to set ContentType in put() method but still not working.
Also its size is showing 0B
Please let me know whats going wrong?
Thanks!
You have certainly reached end of stream.
file.read() has no bytes to read, hence empty file on s3.
Either try file.seek(0) to reset the stream or you must ensure that you are reading file once.
For example:
# You just read the file here.
file.save(os.path.join(UPLOAD_FOLDER, filename))
# file.read() is empty now, you reached to the end of stream
# You are again reading the file here but file.read() is empty, so reset the stream.
file.seek(0)
# file.read() is back to original now
buck.Object(file.filename).put(Body=file.read())
I am using a Flask application to update some PDF files, convert them to an Excel file and send this file back to the user. I am using an instance folder to store the pdf and the excel files.
But when the user press the button "Download" in order to download the generated Excel file, an old file is downloaded (from an older session).
Moreover, when I try to change my code, for example, I changed the name of this Excel file: I can see the new name in the instance folder, but when I download the file with the webapp, it is still the old name (and old file). I have no idea where the webapp is looking for this old file...
MEDIA_FOLDER = '/media/htmlfi/'
app = Flask(__name__)
app.config.from_object(Config)
INSTANCE_FOLDER = app.instance_path
app.config['UPLOAD_FOLDER'] = INSTANCE_FOLDER+MEDIA_FOLDER
#app.route('/file/')
def send():
folder = app.config['UPLOAD_FOLDER']
try:
return send_file(folder+ "file.xlsx", as_attachment=True)
finally:
os.remove(folder+ "file.xlsx")
<a href="{{ url_for('send') }}" ><button class='btn btn-default'>DOWNLOAD</button></a>
I am really new to webapp in general, thank you for your help :)
send_file takes a cache_timeout parameter which is the number of seconds you want to cache the download. By default is 12 hours.
return send_file(
file.file_path(),
as_attachment=True,
cache_timeout=app.config['FILE_DOWNLOAD_CACHE_TIMEOUT'],
attachment_filename=file.file_name
)
http://flask.pocoo.org/docs/1.0/api/
My Objective: I am trying to upload event log file (.evtx), convert it in the backend using LogParser tool into csv, and visualize the data afterward. The Logparser tool will be run by command line using os.system(cmdline_string). Basically I am trying to parse the uploaded file without saving the temporary uploaded file to the file system.
My Problem: I am parsing the event log using Log Parser's command line. I cannot access the temporary uploaded file in appdata\local\temp using log parser's command line.
Code:
uploadfile.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<br>
<button type="submit">Upload</button>
</form>
views.py
import os
import pandas as pd
def uploadfile():
if request.method == 'POST' and 'myfile' in request.FILES:
myfile = request.FILES['myfile']
filename, fileext = os.path.splitext(myfile.name)
if fileext == '.evtx':
cmdstring = "logparser " + \
"\"SELECT * INTO " + "output.csv" + \
" FROM " + myfile.temporary_file_path() + "\" " + \
"-i:EVT -o:CSV"
os.system(cmdstring)
# This will output error:
# Cannot open <from-entity>: Error opening event log /path/to/uploadedfiles:
# The process cannot access the file because it is being used by another process
I am guessing that probably the temporary file is being accessed by django thus logparser cannot access the file. When I tried to save the file into filesystem, logparser is able to access and parse the file. When I simply access and parse any event log data in AppData\Local\Temp directory, it is also manage to do it.
How to let another application access temp uploaded file in django?
My Environment: Windows 10, Python 3.6.1. Django 1.11.4, Log Parser 2.2