django+vue+elementui实现文件下载功能
django文件下载、vue文件下载、elementui文件下载;django和vue实现文件下载
·
图片样式
vue前端代码:
<el-table
height="470"
:data="tableData"
style="width: 100%;"
:default-sort="{prop: 'created', order: 'descending'}"
>
<template slot-scope="scope">
<el-link targer="_blank" :href="`${download_url}?id=${scope.row.id}`">
</el-link>
<el-button
type="primary"
size="mini"
style="color: white"
@click="downloadfile(scope.$index, scope.row)"
>
下载
</el-button>
<br>
<br>
</template>
</el-table-column>
</el-table>
函数编写:
data () {
return {
download_url: '',
}
},
mounted () {
this.download_url = this.$settings.base_url + '/user/downloadfile/'
},
}
downloadfile (index, row) {
var arr=row.filename.split('.')// /medai/companyfile/新员工手册.docx
var file_type=arr[arr.length-1]//获取文件的格式
this.$axios({
method: 'get', // 如果是get方法,则写“GET”
url: this.download_url + `?id=${row.id}`,
responseType: 'blob'
})
.then(res => {
let blob = new Blob([res.data], {
type: 'application/msword' //这里需要根据不同的文件格式写不同的参数
})
let eLink = document.createElement('a')
eLink.download = `${row.name}.${file_type}` //给文件名和指定格式,浏览器下载时看到的
eLink.style.display = 'none'
eLink.href = URL.createObjectURL(blob)
document.body.appendChild(eLink)
eLink.click()
URL.revokeObjectURL(eLink.href)
document.body.removeChild(eLink)
})
.catch(err => {
})
},
后端django代码:
from django.conf import settings
from django.http import FileResponse
class DownloadFileView(GenericAPIView):
def get(self,request):
file_id = request.query_params.get('id')
file_obj = models.CompanyFile.objects.filter(id=file_id).first()
if file_obj:
#拿到文件在数据库中存储的位置
media_file=str(file_obj.filename)
# 拼接文件路径
filepath = os.path.join(settings.MEDIA_ROOT, media_file)
#拿到文件的名字(该名字包含了文件的格式)
filename =media_file.split(r'/')[-1]
file = open(filepath, 'rb')
response = FileResponse(file) # 生成文件对象application/msword application/octet-stream
response['Content-Type'] = 'application/octet-stream'
#name.split('.')[0] + '.docx',
name = filename
response['Content-Disposition'] = 'attachment;filename ="%s"' % (
name.encode('utf-8').decode('ISO-8859-1'))
return response
更多推荐
已为社区贡献8条内容
所有评论(0)