FaterCSV Encoding Issue - ruby-1.8.7

I am using fastercsv gem for csv export with utf-8 encoding.
When ever i export any arabic content in my csv using utf-8 , when i try to open in windows it comes out as some strange characters. where as in ubuntu it comes fine.
I am working with ruby 1.8.7.
fastercsv (1.5.5)
rails 2.3.5
csv_string=FasterCSV.generate(:encoding => 'utf-8') do |csv|
csv << header_col
csv << data_col
end
filename = "Print- #{Time.now.to_date.to_s}.xls"
send_data(csv_string, :type => 'text/xls; charset=utf-8; header=present', :filename => filename)

this has worked for me
csv_string=FasterCSV.generate(:col_sep => "\t") do |csv|
end
send_data Iconv.conv("utf-16", "utf-8", csv_string),:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=#{filename}.csv"

Related

django download view downloading only .xls instead of file with extension on model

I have my Django view where I upload the file from admin and users download it on the frontend when I download the file on the frontend the download is extension with only .xls i.e when I upload the file with .xlsx extension it is still downloading with .xls instead the file should be downloaded according to the extension either its xls or xlsx.
views.py
class myAPIView(APIView):
def get(self, request):
data = Model.objects.first()
filename = data.file.name
file_extention = filename.split('.')[-1]
response = HttpResponse(
data.file.path,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = \
'attachment; filename="output_file"'+ file_extention
return response
This is the standard that you can apply(edit the content-type for you.)
class myAPIView(APIView):
def get(self, request):
data = Model.objects.first()
filename = data.file # or data.file.name based on your models.
file_extention = filename.split('.')[-1] # something which is seprated by dot. in the last
response = HttpResponse(
file_path,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = \
'attachment; filename="output_file"'+ file_extention
return response

Getting corrupt zips using Python3 ZipStream in Django

I'm using zipstream from here and have a Django view that returns a zip file of all file attachments which are all hosted on Amazon S3. But the zip files are all coming up as corrupt when I download them, that is, I can't open them.
import io
import zipstream
s = io.BytesIO()
with zipstream.ZipFile(s,"w", compression=zipstream.ZIP_DEFLATED) as zf:
for file_path in file_paths:
file_dir, file_name = os.path.split(file_path)
zf.writestr(file_name, urllib.urlopen(file_path).read())
response = StreamingHttpResponse(s.getvalue(), content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename={}'.format('files.zip')
return response
Instead of zipstream package install aiozipstream package. If you've alreday installed the zipstream package uninstall it first.
pip uninstall zipstream and then do a
pip install aiozipstream
#Do the import in the same way
from zipstream import ZipStream
from django.http import StreamingHttpResponse
def s3_content_generator(key):
#s3_bucket - your s3 bucket name
infile_object = s3.get_object(Bucket=s3_bucket, Key= key)
data = str(infile_object.get('Body', '').read())
yield bytes(data, 'utf-8')
files = []
#filepath - list of s3 keys
for keyin filepath:
files.append({'stream': s3_content_generator(key),'name': 'filename'})
#large chunksize fasten the download process
zf = ZipStream(files, chunksize=32768)
response = StreamingHttpResponse(zf.stream(), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename={}'.format('files.zip')
return response

Problem with headers generation in image upload Python 3

I´m trying to upload an image with Python 3, this is my upload method:
def load():
headers = {'X-API-Key' : adminTokenSession}
image= {'image': open ('C:/Users/Cesar/Desktop/A-FT-DIVT.jpg', 'rb')}
res = requests.post(activityInfoURL, files= image, headers = headers)
print (res.text)
In the server I check if format is jpg or png like this:
if (files.image[0].headers['content-type'] != 'image/jpeg' && files.image[0].headers['content-type'] != 'image/png') {
logger.warn("Trying to upload a different format file")
res.json({ error: "The file must be an image" })
I´m always getting "The file must be an image" error and I think it´s because headers are not created.
Thanks in advance.
You may want to post an image, instead of an open file descriptor:
headers = {'X-API-Key' : adminTokenSession}
# Note here
with open('C:/Users/Cesar/Desktop/A-FT-DIVT.jpg', 'rb') as f:
image = {'image': f.read()}
# Note: ^^^^^^^^
res = requests.post(activityInfoURL, files= image, headers = headers)

Determine if url is a pdf or html file

I am requesting urls using the requests package in python (e.g. file = requests.get(url)). The urls do not specify an extension in them, and sometimes a html file is returned and sometimes a pdf is returned.
Is there a way of determining if the returned file is a pdf or a html, or more generally, what the file format is? The browser is able to determine, so I assume it must be indicated in the response.
This will be found in the Content-Type header, either text/html or application/pdf
import requests
r = requests.get('http://example.com/file')
content_type = r.headers.get('content-type')
if 'application/pdf' in content_type:
ext = '.pdf'
elif 'text/html' in content_type:
ext = '.html'
else:
ext = ''
print('Unknown type: {}'.format(content_type))
with open('myfile'+ext, 'wb') as f:
f.write(r.raw.read())

Why is my excel add-in getting corrupted?

I have a link to an excel add-in I let users download. I am using flask + mod_wsgi.
#app.route('/link/')
def download_addin():
parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '/static/'
response = make_response()
response.headers['Cache-Control'] = 'no-cache'
response.headers['Content-Type'] = 'application/vnd.ms-excel.addin.macroEnabled.12'
response.headers['Content-Disposition'] = 'attachment; filename=my_addin.xlam'
return response
I download the file but when I use it in Excel I get a warning "Excel cannot open the file 'my_addin.xlam' because the file format or file extension is not valid...'
Thanks!
You need to return the file as part of the response. Try something like
#app.route('/link/')
def download_addin():
parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '/static/'
with open(os.path.join(parent_dir, 'my_addin.xlam')) as f:
response = make_response(f.read())
response.headers['Cache-Control'] = 'no-cache'
response.headers['Content-Type'] = 'application/vnd.ms-excel.addin.macroEnabled.12'
response.headers['Content-Disposition'] = 'attachment; filename=my_addin.xlam'
return response
Without doing this you'll download an empty file. That's probably why Excel doesn't like the format.

Resources