我使用Yii2框架。我想显示文件上传进度。我不需要带有拖放或预览功能的复杂界面。只有进度条和可能的“取消”按钮。您能指出一个简单的例子吗?谢谢。
答案 0 :(得分:0)
最终我用jQuery ajax做到了。
js:
function upload() {
var input = $('#archiveInput');
var files = input.prop('files');
if (files.length > 0) {
var data = new FormData();
data.append('archive', files[0]);
$.ajax({
url: input.data('upload-url'),
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Upload Complete');
},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', onProgress);
return myXhr;
}
}
});
}
}
function onProgress(ev) {
if (ev.lengthComputable) {
var progress = parseInt(ev.loaded / ev.total * 100, 10);
$("#progress .progress-bar").css(
"width",
progress + "%"
);
}
}
php控制器:
public function actionUpload($idSupply)
{
$directory = FileHelper::normalizePath(Yii::getAlias('@app') . '/uploads/' . $idSupply);
if (!is_dir($directory)) {
FileHelper::createDirectory($directory);
}
$fileName = 'archive.zip';
$filePath = $directory . DIRECTORY_SEPARATOR . $fileName;
if (is_file($filePath)) {
unlink($filePath);
}
move_uploaded_file($_FILES['archive']['tmp_name'], $filePath);
}