文件上传进度条干扰控制器重定向
Posted
技术标签:
【中文标题】文件上传进度条干扰控制器重定向【英文标题】:File upload progress bar interferes with Controller redirect 【发布时间】:2021-11-16 10:23:43 【问题描述】:我有一个文件提交表单和一个跟踪上传进度的进度条。但是,控制进度条的 javascript 会干扰我的控制器,我不知道如何修复它。我的控制器从不使用链接重定向回家(它在没有实现进度条的情况下工作)。删除 window.location.href="/";
并不能解决此问题。
任何想法如何解决这个问题?
home.blade.php
<form action="route('file.store')" method="post" class="w-100" enctype="multipart/form-data">
@csrf
<div class="progress" id="progressBar">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<br>
<div class="custom-file overflow-hidden rounded-pill mb-3">
<input id=“file type="file" class="custom-file-input rounded-pill" name="file">
<label id="fileName" for=“file” class="custom-file-label rounded-pill">Choose file</label>
</div>
<input type="submit" class="file-upload btn btn-primary btn-block rounded-pill shadow mb-3" id="uploadButton">
</form>
文件控制器.php
public function store(Request $request)
// Process the file
$link = “https://example.com”;
session()->flash("link",$link);
// return back to home with link to download the file
return redirect()->back();
Javascript
$(document).ready(function()
document.getElementById("progressBar").style.display = "none";
var bar = $('.bar');
var percent = $('.percent');
$('form').ajaxForm(
beforeSend: function()
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
document.getElementById("progressBar").style.display = "";
document.getElementById('uploadButton').disabled = true;
,
uploadProgress: function(event, position, total, percentComplete)
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
,
complete: function(xhr)
document.getElementById("progressBar").style.display = "none";
document.getElementById('uploadButton').disabled = false;
window.location.href="/";
);
);
【问题讨论】:
进度条使用 vue.js 更容易 【参考方案1】:使用这个
public function uploadMultipleFile(Request $request)
foreach($request->file('file') as $image)
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
Gallery::insert(['title' => $new_name]);
$res = array(
'success' => 'Multiple Image File Has Been uploaded Successfully'
);
return response()->json($res);
<script>
$(document).ready(function()
$('form').ajaxForm(
beforeSend:function()
$('#success').empty();
$('.progress-bar').text('0%');
$('.progress-bar').css('width', '0%');
,
uploadProgress:function(event, position, total, percentComplete)
$('.progress-bar').text(percentComplete + '0%');
$('.progress-bar').css('width', percentComplete + '0%');
,
success:function(data)
if(data.success)
$('#success').html('<div class="text-success text-center"><b>'+data.success+'</b></div><br /><br />');
$('#success').append(data.image);
$('.progress-bar').text('Uploaded');
$('.progress-bar').css('width', '100%');
);
);
</script>
【讨论】:
以上是关于文件上传进度条干扰控制器重定向的主要内容,如果未能解决你的问题,请参考以下文章