Django+Vue实现各样式文件下载

     阅读:51

Django:

# 这里返回一个迭代器,防止文件过大将内存打满,这样可以保证服务的占用内存几乎没有波动
def read_file(file_name, buf_size=409600):
    with open(file_name, "rb") as f:
        while True:
            c = f.read(buf_size)
            if c:
                yield c
            else:
                break


@action(detail=False, methods=['POST'])
def export_templates(self, request, *args, **kwargs):
	file_name = "取的名字根据项目上下文决定"
	# 使用文件流的方式返回
	res = StreamingHttpResponse(read_file(file_name))
	# 增加headers
	res['Content-Type'] = 'application/octet-stream'
	res['Access-Control-Expose-Headers'] = "Content-Disposition, Content-Type"
	res['Content-Disposition'] = "attachment;"
	return res

Vue:

这里对axios的封装就不说了
axios请求的参数: url,方法名,参数,responseType要带上:
url: ‘xxxx’,
method: ‘post’,
responseType: ‘blob’,
data
请求后返回的response处理:

	.then(response => {
		const filename = "xxx" + '.tar'
		const blob = new Blob([response], {
		  type: 'application/x-tar'
		})
		// console.log("fileName",fileName)
		if (window.navigator.msSaveOrOpenBlob) {
		  navigator.msSaveBlob(blob, filename)
		} else {
		  var link = document.createElement('a')
		  link.href = window.URL.createObjectURL(blob)
		  link.download = filename
		  link.click()
		  // 释放内存
		  window.URL.revokeObjectURL(link.href)
		}
	})

tips:

  • blob的type选择:

参考自:https://blog.csdn.net/Zhuangvi/article/details/121063203

后缀名文件类型类型(type)
.xlsMicrosoft Excelapplication/vnd.ms-excel
.xlsxMicrosoft Excel (OpenXML)application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.csvCSVtext/csv
.docMicrosoft Wordapplication/msword
.docxMicrosoft Word (OpenXML)application/vnd.openxmlformats-officedocument.wordprocessingml.document
.pdfPDFapplication/pdf
.pptMicrosoft PowerPointapplication/vnd.ms-powerpoint
.pptxMicrosoft PowerPoint (OpenXML)application/vnd.openxmlformats-officedocument.presentationml.presentation
.png便携式网络图形(PNG)image/png
.gifGIFimage/gif
.jpegJPEG 图片image/jpeg
.jpgJPEG 图片image/jpeg
.mp3MP3 音频audio/mpeg
.aacAAC 音频audio/aac
.html超文本标记语言 (HTML)text/html
.cssCSStext/css
.jsJavaScripttext/javascript
.jsonJSON 格式application/json
.abwAbiWord 文档application/x-abiword
.arc存档文档(多个文件嵌入)application/x-freearc
.aviAVI: 音频视频交错video/x-msvideo
.azw亚马逊Kindle电子书格式application/vnd.amazon.ebook
.bin任何类型的二进制数据application/octet-stream
.bmpWindows OS/2位图图形image/bmp
.bzBZip 存档application/x-bzip
.bz2BZip2 存档application/x-bzip2
.cshC-Shell 脚本application/x-csh
.eotMS嵌入式OpenType字体application/vnd.ms-fontobject
.epub电子出版物(EPUB)application/epub+zip
.htm超文本标记语言 (HTML)text/html
.icoIcon 格式image/vnd.microsoft.icon
.icsiCalendar 格式text/calendar
.jarJava Archive (JAR)application/java-archive
.jsonldJSON-LD 格式application/ld+json
.mid乐器数字接口(MIDI)audio/midi audio/x-midi
.midi乐器数字接口(MIDI)audio/midi audio/x-midi
.mjsJavaScript 模块text/javascript
.mpegMPEG 视频video/mpeg
.mpkg苹果安装程序包application/vnd.apple.installer+xml
.odpOpenDocument演示文档application/vnd.oasis.opendocument.presentation
.odsOpenDocument 电子表格文件application/vnd.oasis.opendocument.spreadsheet
.odtOpenDocument 文本文档application/vnd.oasis.opendocument.text
.ogaOGG 音频audio/ogg
.ogvOGG 视频video/ogg
.ogxOGGapplication/ogg
.otfOpenType 字体font/otf
.rarRAR 存档application/x-rar-compressed
.rtf富文本格式 (RTF)application/rtf
.shBourne shell 脚本application/x-sh
.svg可缩放矢量图形 (SVG)image/svg+xml
.tarTape 归档(TAR)application/x-tar
.tif标记图像文件格式 (TIFF)image/tiff
.tiffTagged Image File Format (TIFF)image/tiff
.ttfTrueType 字体font/ttf
.txtTexttext/plain
.vsdMicrosoft Visioapplication/vnd.visio
.wav波形音频格式audio/wav
.webaWEBM 音频audio/webm
.webmWEBM 视频video/webm
.webpWEBP 图片image/webp
.xhtmlXHTMLapplication/xhtml+xml
.xmlXMLapplication/xml(普通用户不可读)、text/xml(普通用户可读)
.xulXULapplication/vnd.mozilla.xul+xml
.zipZIPapplication/zip
.3gp3GPPaudio/video 容器 video/3gpp、audio/3gpp(不含视频)
.3g23GPP2audio/video 容器 video/3gpp2、audio/3gpp2(不含视频)
.7z7-zipapplication/x-7z-compressed
.swf小型web格式 (SWF) or Adobe Flash documentapplication/x-shockwave-flash
.woff网页开放字体格式 (WOFF)font/woff
.woff2网页开放字体格式 (WOFF)font/woff2