文件下载

(一)前端页面展示

 (二)路由展示

(三)试图函数展示

文件路径

 代码:

from django.http import HttpResponse, FileResponse

def download_template(request):

  file = open('static/files/BatchPayTemplate.xls', 'rb')

  response = FileResponse(file)

  response['Content-Type'] = 'application/octet-stream'

  response['Content-Disposition'] = 'attachment;filename="BatchPayTemplate.xls"'

  return response

 

图片下载

 后端

 

 

 将图片转为二进制数据流

class stonehomeimg_download(APIView):
def post(self,request):
obj =models.StoneHome.objects.filter(stone_chinaname=request.data["stone_chinaname"]).first()
if obj:
res = ser.StonehomeSerializer(obj)
ps = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"media\stonehomeimg_download",res.data["stone_encode"]+"-GQ.png")
file = open(ps, 'rb')
img_download = FileResponse(file)
img_download['Content-Type'] = 'application/octet-stream'
img_download['Content-Disposition'] = 'attachment;filename="BatchPayTemplate.png"'
return img_download
else:
return response.APIResponse(code=1, msg="worring")

前端

 

 

download() {
this.$axios({
url: this.$settings.base_url + "stonehomeimg_download/",
method: "post",
responseType: "blob",
data: {
stone_chinaname: this.stone_chinaname,
},
})
.then((response) => {
const blog = new Blob([response.data], { type: "image/png" }); //接收后端返回的二进制数据流
const url = window.URL.createObjectURL(blog); //将数据流转为blob的url链接
      const a = document.createElement("a");        //  创建a标签
a.download = "trendex.png"; // 下载名称
a.href = url; // 下载链接
a.click(); // a点击
})
.catch((error) => {});
},

posted on 2021-02-10 20:28  Plyc  阅读(59)  评论(0编辑  收藏  举报

导航