VUE
<template>
<div>
<button @click="downloadFile" id="btn">下载文件</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
methods: {
downloadFile() {
const filename = '1.docx'; // 文件名,根据需求进行设置
axios.post('http://127.0.0.1:8000/api/videodownload/', { filename }, {responseType: 'blob'})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.dir(response)
})
.catch(error => {
console.error('文件下载失败', error);
});
}
};
</script>
DJANGO
@csrf_exempt
def videodownload(request):
body_unicode = request.body.decode('utf-8')
data = json.loads(body_unicode)
filename = data.get('filename')
download_file_path = os.path.join(settings.BASE_DIR, "studownload", filename)
if os.path.exists(download_file_path):
response = FileResponse(open(download_file_path, 'rb'),filename=filename,)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition']= 'attachment'
return response
else:
return JsonResponse({'status': 'HttpResponse', 'msg': 'Excel下载失败'})
可以下载文件,但是打不开
只有txt格式的文件可以正常打开
返回的response中的data均为乱码
求帮助解决