我想在服务器上下载文件,我尝试了以下代码,但文件未下载。我将多个文件合并为单个文件,然后合并后我希望下载结果文件。现在在result.docx中合并文件,但不会自动下载
我在ajax响应中返回完整的文件路径
脚本
$("#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;
}
});
});
控制器
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';
}
作为回报,我收到'D:\xampp\zerodocs\public\uploads\complete_specs\4\files\result.docx'
答案 0 :(得分:0)
最简单的解决方案是使用浏览器下载它,而不是使用javascript fs,因为它存在数据损坏的风险。
此函数创建href标记并单击以初始化下载。希望有帮助
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);
}