在vue框架中:
https://mp.weixin.qq.com/s/Rdc-PcQCQstgC1QubwTO_Q
在mako框架中只能先将excel放在一个固定的文件夹下,例如:upload目录下,然后获取到其绝对路径传到前端即可。
<%inherit file="/base.html"/>
<%block name="content">
<div id="app">
<a :href="site_url + 'download_word_?url=' + file_path_">点击下载</a>
</div>
</%block>
<script>
Vue.prototype.$http = axios;
Vue.use(iview);
new Vue({
el: '#app',
data() {
return {
site_url: window.site_url,
file_path_: '',
}
},
methods: {
get_path() {
this.$http.get('${SITE_URL}get_path/').then(res => {
if (res.data.result) {
this.file_path_ = res.data.path
} else {
this.$Message.error(res.data.message)
}
})
}
},
mounted() {
this.get_path()
}
})
</script>
<style></style>
特别注意的是不能用\斜杠,否则会报错,对应后端代码为:
def get_path(request):
try:
path = PROJECT_ROOT + '/upload/new.xlsx'
except Exception as e:
return render_json({'result': False, 'message': "获取路径失败"})
return render_json({'result': True, 'path': path})
def download_word_(request):
# 获取前端传递过来的保存文件的url
url = request.GET.get('url')
if url is None:
return render_json({'result': False, 'data': '请传入文件路径参数url'})
name_li = url.split('/')
file_name = name_li[-1]
# 获取文件名
file_name = file_name.split('/')[-1]
f = open(url, 'rb')
response = HttpResponse(f)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment;filename*=utf-8''{}".format(escape_uri_path(file_name))
return response