[英]How to force download a file when get file path in ajax response
I want to download file on my server i have the following code that i tried but file is not downloading.我想在我的服务器上下载文件我尝试了以下代码,但文件没有下载。 i am merging multiple files into single file then after merger i want the result file to download.
我将多个文件合并为单个文件,然后在合并后我希望下载结果文件。 Now files merger in result.docx but not download automatically
现在文件合并在 result.docx 中,但不会自动下载
i am returning complete file path in ajax response我在 ajax 响应中返回完整的文件路径
Script脚本
$("#download_specs").click(function(){
var slug = this.getAttribute('data-id');
$.ajax({
url:"{{url('merge-document')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{slug:slug} ,
success:function(data){
var zz=document.createElement('a');
zz.href = data;
}
});
});
Controller Controller
public function mergeDocuments(Request $request){
$project_slug = $request->input('slug');
$userID = Auth::user()->id;
$files = DB::table('project_specs_files')->select('completed_specs')->where('user_id',$userID)->where('project_slug',$project_slug)->get();
$specs_array = array();
foreach($files as $file){
$ext = pathinfo(public_path(). '\\uploads\\complete_specs\\'.$userID.'\\files\\'.$file->completed_specs, PATHINFO_EXTENSION);
if($ext == 'docx'){
if (file_exists(public_path(). '\\uploads\\complete_specs\\'.$userID.'\\files\\'.$file->completed_specs)){
$specs_array[] = public_path(). '\\uploads\\complete_specs\\'.$userID.'\\files\\'.$file->completed_specs ;
}
}
}
if(!empty($specs_array)){
$dir = public_path(). '\\uploads\\complete_specs\\'.$userID.'\\files\\';
$dm = new DocxMerge();
$dm->merge($specs_array, $dir.'result.docx' );
}else{
return 'Files not supported for merge';
}
return $dir.'result.docx';
}
in return im receiving 'D:\xampp\zerodocs\public\uploads\complete_specs\4\files\result.docx'
作为回报,我收到
'D:\xampp\zerodocs\public\uploads\complete_specs\4\files\result.docx'
The easiest solution is using the browser to download it instead of using javascript fs as it has the risk of data corruption.最简单的解决方案是使用浏览器下载它,而不是使用 javascript fs,因为它有数据损坏的风险。
This function creates a href tag and clicks it to init download.这个 function 创建一个 href 标签并点击它来初始化下载。 Hope that helps
希望有帮助
function _downloadUrlContent(url) { const a = document.createElement('a'); a.href = url; a.download = ''; a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.