How to open a .txt file in Django? - python

I have a Django app in which when I click on the link then I can download a .txt file. Now instead of downloading that file I need to open that file (in 'r' mode). I'm trying to do something similar to that of mail attachments that is when we click on the attachment then it opens up instead of downloading. How can I do it ? The following code is to download the .txt file :
def fetch_logfile(request,logfile):
try:
folder,log,_ = logfile.split("/")
pathRelative = r"/LogFile/"+log
folder,log,_ = logfile.split("/")
pathRelative = r"/LogFile/"+log
path = pathRelative[1::]
os.startfile(pathRelative,open)
file_path =os.getcwd()+ '/' +pathRelative
file_wrapper = FileWrapper(file(file_path,'rb'))
file_mimetype = mimetypes.guess_type(file_path)
response = HttpResponse(file_wrapper, content_type=file_mimetype )
response['X-Sendfile'] = file_path
response['Content-Length'] = os.stat(file_path).st_size
nameOnly = log.split('/')
response['Content-Disposition'] = 'attachment; filename=%s' % nameOnly[len(nameOnly)-1]
return response
except:
## do something else
The following code works which I have tried in Python IDLE but when I try the same in Django then it doesn't work. I'm not sure if this is the right way either.Please advice me on this.
def fetch_Logfile(request,logfile):
import os,sys
path = "C:\\Users\\welcome\\Desktop\\mysite\\LogFile\\"+"756849.txt"
os.startfile(path,open)
## do something with logfile and request
def fetch_Logfile(request,logfile):
path = "C:\\Users\\welcome\\Desktop\\mysite\\LogFile\\"+"756849.txt"
import webbrowser
webbrowser.open(path)
## do something with logfile and request
def fetch_Logfile(request,logfile):
import win32api,os,subprocess
path = "C:\\Users\\welcome\\Desktop\\mysite\\LogFile\\"+"756849.txt"
filename_short = win32api.GetShortPathName(path)
subprocess.Popen('start ' + filename_short, shell=True )
subprocess.Popen('start ' + path, shell=True )
## do something with logfile and request

my_file = open(file_path, 'r')
response = HttpResponse(my_file.read(), mimetype='text/plain')
response['Content-Disposition'] = 'inline;filename=some_file.txt'
return response
Here is the MIME Types – Complete List
You can provide mimetype = ' / ' based on the file extension by referencing the mime type list.

Related

django error:can't specify the download filename

def download(request):
f = open("next_op.xls")
data = f.read()
f.close()
response = HttpResponse(data, content_type = './application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="nextop.xls"'
return response
When I use this code, I can download the file correctly, but the file name is invalid. I get the file name "download", and I found the response header doesn't include the Content-Disposition after I download the file.
you may need this:
fd = open(file, 'rb')
return FileResponse(fd, as_attachment=True, filename='xxx')

Python - create txt file on the fly and send it via FTP?

So i am currently creating a text file from a jinja2 template on the fly and having it be downloaded by the users browser, however i want to add an option to send it somewhere via FTP (all the FTP details are predefined and wont change)
how do i create the file to be sent?
Thanks
code:
...
device_config.stream(
STR = hostname,
IP = subnet,
BGPASNO = bgp_as,
LOIP = lo1,
DSLUSER = dsl_user,
DSLPASS = dsl_pass,
Date = install_date,
).dump(config_file)
content = config_file.getvalue()
content_type = 'text/plain'
content_disposition = 'attachment; filename=%s' % (file_name)
response = None
if type == 'FILE':
response = HttpResponse(content, content_type=content_type)
response['Content-Disposition'] = content_disposition
elif type == 'FTP':
with tempfile.NamedTemporaryFile() as temp:
temp.write(content)
temp.seek(0)
filename = temp.name
session = ftplib.FTP('192.168.1.1','test','password')
session.storbinary('STOR {0}'.format(file_name), temp)
session.quit()
temp.flush()
return response
EDIT
needed to add temp.seek(0) before sending the file
You can use the tempfile module to create a named temporary file.
import tempfile
with tempfile.NamedTemporaryFile() as temp:
temp.write(content)
temp.flush()
filename = temp.name
session.storbinary('STOR {0}'.format(file_name), temp)
Here is a working example using BytesIO under io module. Code is tested and works.
import ftplib
import io
session = ftplib.FTP('192.168.1.1','USERNAME','PASSWORD')
# session.set_debuglevel(2)
buf=io.BytesIO()
# b'str' to content of buff.write() as it throws an error in python3.7
buf.write(b"test string")
buf.seek(0)
session.storbinary("STOR testfile.txt",buf)
session.quit()

Django serves file.tar.gz not compressed

I have made a view to serve some file.tar.gz but when I download it, the file is not compressed.
Files on server, where my app is running has 63 438 bytes:
-rw-r--r-- 1 root root 63448 Nov 5 14:13 file.tar.gz
but when I download it it has 716 800 bytes.
This is my downloading function:
def download_logs(request):
""" View returning file to download """
file_path = request.GET['filepath']
original_filename = file_path.split("/")[-1]
try:
file_loaded = open(file_path, 'rb')
except IOError as err:
LOG.debug(err)
LOG.debug("File %s does not exist", file_path)
return error_view(request, "IOError", "File no longer exists.")
response = HttpResponse(file_loaded.read(), 'application/x-gzip')
file_loaded.close()
file_type, encoding = mimetypes.guess_type(original_filename)
if file_type is None:
file_type = 'application/octet-stream'
response['Content-Type'] = file_type
response['Content-Length'] = str(os.stat(file_path).st_size)
if encoding is not None:
response['Content-Encoding'] = encoding
# To inspect details for the below code, see http://greenbytes.de/tech/tc2231/
if u'WebKit' in request.META['HTTP_USER_AGENT']:
# Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly.
filename_header = 'filename=%s' % original_filename.encode('utf-8')
elif u'MSIE' in request.META['HTTP_USER_AGENT']:
# IE does not support internationalized filename at all.
# It can only recognize internationalized URL, so we do the trick via routing rules.
filename_header = ''
else:
# For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers).
filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(original_filename.encode('utf-8'))
response['Content-Disposition'] = 'attachment; ' + filename_header
return response
I image that there is a problem with the way how I open the file, I just could not find right solution.
If you need to serve a tar.gz file do this,
tar = tarfile.open("file_name.tar.gz", "r")
response = HttpResponse(tar, content_type='application/tar+gzip')
response['Content-Disposition'] = 'attachment; filename="file_name.tar.gz"'
return response
As Klaus D. said in comment this was a problem with encoding.
When I changed
if encoding is not None:
response['Content-Encoding'] = encoding
to
response['Content-Encoding'] = 'tar'
Everything stated to working properly.

Django define name of file to serve

I have wrote a code which let user to download a file. This is the code :
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
return serve(request, filename, os.path.dirname(filepath))
I want to define the file name that user will download. At the moment, the name of downloaded file is the URL after my domain name.
Do you know how to define the name of file downloaded by user ?
You need to set the Content-Dispositionheader in your response. First of all you shouldn't use the serve() view, to deliver the file, because it only works as long as DEBUG = True is set.
With a look at the Django Docs something like the following should do the trick
def download_file(request, ref):
filepath = "/home/jedema/code_"+ref+".txt"
filename = os.path.basename(filepath)
final_filename = "code.txt"
with open(filepath) as f:
response = HttpResponse(f.read(), content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s"' % final_filename
return response
I haven't tested it but it should be a hint into the right direction

Unknown and Damaged Archive in django

This is code to download files but when file downloads and i open them :the archive is unknown and damaged. Can you please help me to solve this problem here code is:
def download(request):
file_name =request.GET.get('file_name', '')
the_file = "C:\\Users\\CV_Uploads\\uploadfiles\\uploadfiles\\uploaded_files\\1395901478_89_uploadfiles.rar"
filename = os.path.basename(the_file)
response = HttpResponse(FileWrapper(open(the_file)),
content_type=mimetypes.guess_type(the_file)[0])
response['Content-Length'] = os.path.getsize(the_file)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
When you are dealing with paths you should use raw string .
use
the_file = r"C:\Users\CV_Uploads\uploadfiles\uploadfiles\uploaded_files\1395901478_89_uploadfiles.rar"

Categories

Resources