[英]download a url file with javascript istead of opening the file
I want to download a file from the server using javascript/jquery. 我想使用javascript / jquery从服务器下载文件。
When press the button the server response with an url file that i want to download. 当按下按钮时,服务器将响应我要下载的url文件。
the button: 按钮:
<a class="btn btn-primary" id="exportInvoice">Export XML</a>
the ajax request: ajax请求:
$('#exportInvoice').on('click', function () {
$.ajax({
type: 'POST',
dataType: 'json',
url: '{{ route('export-xml') }}',
data: {dateRange: dateRange},
success: function (resp) {
if(resp.error){
// error
alert(resp.msg);
} else {
// success
alert(resp.msg);
window.location=resp.url;
}
}
});
})
I am using laravel 5.7 blade to generate the url. 我正在使用laravel 5.7刀片来生成URL。
When i click the button the file will open instead of download (because of the window.location=resp.url; 当我单击按钮时,文件将打开而不是下载(由于window.location = resp.url;
I was thinking... after the ajax call is made (when success response).... setting the download attribute and href to the link.... but then i need to call again the click event to download the file. 我在想...进行ajax调用后(成功响应时)....将download属性和href设置为链接....但是我需要再次调用click事件以下载文件。
How can i download the file istead of opening??? 我如何下载文件而不是打开???
window.location.href = resp.url
这将在同一页面上开始下载,就像您单击链接时没有_self
以外的任何其他目标一样。
creating a hidden form for download the file works: 创建用于下载文件的隐藏表单的工作原理是:
The hidden form: 隐藏形式:
<form id="downloadXmlForm" method="post" action="{{ route('download-xml-invoices') }}" style="display: none">
<input type="hidden" name="xmlFileName">
<button type="submit" class="btn btn-primary">Export XML</button>
({ csrf_field() }}
</form>
After receiving from ajax request (on success) => submit the form to download the file: 从ajax请求收到(成功后)=>提交表单以下载文件:
$('input[name="xmlFileName"]').val(resp.fileName);
document.getElementById('downloadXmlForm').submit();
On the backend the response for the ajax request is: 在后端,ajax请求的响应为:
...
$fileName = uniqid().'.xml';
$xmlFilePath = storage_path('invoices/'.$fileName);
file_put_contents($xmlFilePath, $xmlString);
return response()->json(['error' => false, 'msg' => $message, 'fileName' => $fileName]);
The download function that is call on form submit: 调用表单提交的下载功能:
public function downloadInvoicesXml(Request $request){
return response()->download( storage_path('invoices/'.$request->input('xmlFileName')));
}
If anyone have any better idea, please tell me :) 如果有人有更好的主意,请告诉我:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.