hyhyhy

// 下载接口文档
DownloadApi() {
$.ajax({
type: "get",
url: test+"/api/api/Download",
async: true,
data: { project_id: this.$route.params.project_id},
headers: {
Authorization: \'Token \'+JSON.parse(sessionStorage.getItem(\'token\'))
},
timeout: 5000,
success: function(data) {
if (data.code === "999999") {
window.open(test+"/api/api/download_doc?url="+data.data)
}
},
})
},

--------------------------------------------------------------

 

class DownLoad(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = ()

def get(self, request):
"""
获取Api下载文档路径
:param request:
:return:
"""
project_id = request.GET.get("project_id")
try:
if not project_id.isdecimal():
return JsonResponse(code="999996", msg="参数有误!")
except AttributeError:
return JsonResponse(code="999996", msg="参数有误!")
try:
obj = Project.objects.get(id=project_id)
except ObjectDoesNotExist:
return JsonResponse(code="999995", msg="项目不存在!")
pro_data = ProjectSerializer(obj)
if not pro_data.data["status"]:
return JsonResponse(code="999985", msg="该项目已禁用")

obi = ApiGroupLevelFirst.objects.filter(project=project_id)
data = ApiInfoDocSerializer(obi, many=True).data
obn = ApiInfoSerializer(ApiInfo.objects.filter(project=project_id), many=True).data
url = Write().write_api(str(obj), group_data=data, data=obn)
print(url)
return JsonResponse(code="999999", msg="成功!", data=url)


def download_doc(request):
url = request.GET.get("url")
print(url)
format_doc = url.split(".")
if format_doc[-1] == "docx":
file_name = str(int(time.time())) + ".docx"
else:
file_name = str(int(time.time())) + ".xlsx"
print(file_name)

def file_iterator(_file, chunk_size=512):
while True:
c = _file.read(chunk_size)
if c:
yield c
else:
break

_file = open(url, "rb")
response = StreamingHttpResponse(file_iterator(_file))
response["Content-Type"] = "application/octet-stream"
response["Content-Disposition"] = "attachment;filename=\"{0}\"".format(file_name)
return response

分类:

技术点:

相关文章: