def response_for_download_zip(folder, maxFileSize = MAX_ZIP_FILE_SIZE): """ Preparing response for downloading zip-file, consist of all files in folder (without recursion!) Content-Disposition header field from http://tools.ietf.org/html/rfc2183 :param: folder - instance of Folder model :return: HttpResponse with zip file and some parameters Message in case of zip file overflow max size """ zipSubdir = folder.name zipFilename = "%s.zip" % folder.name sio = BytesIO() # Open StringIO to grab in-memory ZIP contents zipFile = zipfile.ZipFile(sio, "w") # The zip compressor zipFileSize = 0 msg = "" for report in Report.objects.filter(parent_id=folder.id): zipFileSize += report.file.size if zipFileSize > maxFileSize: msg = 'Завеликий zip. Решту файлів відкинуто' break filename = report.filename # "людська" назва файла filepath = report.file.name # шлях до файла на диску abs_path = os.path.join(MEDIA_ROOT, filepath) zipPath = os.path.join(zipSubdir, filename) # шлях в архіві zipFile.write(abs_path, zipPath) # add file to zip zipFile.close() # Must close zip for all contents to be written fileExt = ".zip" ct = get_mimeType().get(fileExt.lower(), "application/octet-stream") fn = ' filename="%s";' % transliterate(zipFilename) fns = " filename*=utf-8''%s;" % urlquote(zipFilename) # Grab ZIP file from in-memory, make response with correct MIME-type response = HttpResponse(sio.getvalue(), content_type=ct) response['Content-Disposition'] = 'attachment' + fn + fns response['Content-Length'] = len(sio.getbuffer()) return response, zipFilename, msg
def response_for_download(report, cd_value='attachment'): """ Preparing response for downloading file Content-Disposition header field from http://tools.ietf.org/html/rfc2183 :param: report - instance of Report model :param: cd_value - Content Disposition Value: "attachment" - for download "inline" - for preview :return: HttpResponse with report.file and some parameters """ path = report.file.path fileExt = os.path.splitext(report.filename)[1] # [0] returns path+filename ct = get_mimeType().get(fileExt.lower(), "application/octet-stream") filename = report.filename cdv = '%s; ' % cd_value fn = 'filename="%s"; ' % transliterate(filename) fns = "filename*=utf-8''%s; " % urlquote(filename) md = 'modification-date="%s"; ' % report.uploaded_on response = HttpResponse(content_type=ct) # content = report.file.read() with open(path, 'rb') as file: content = file.read() # читаємо файл незалежно від report # (інакше при тестуванні не завжди # вдається видалити тимчасовий файл) response.write(content) response['Content-Disposition'] = cdv + fn + fns + md response['Content-Length'] = report.file.size return response
def file_media_type(f): # Фільтр для медіатипу файла try: e = os.path.splitext(f.filename)[1] # [0] returns path+filename mt = get_mimeType().get(e.lower(), "") except: mt = "" return mt