官网链接
Bootstrap File Input - © Kartik
引用官网示例
Client Code Example
var $wvLinkInput = $('#wv_link_full');
$wvLinkInput.fileinput({
language: 'zh',
uploadUrl: '<?php echo Yii::$app->urlManager->createUrl(['file/works-list']);?>',
initialPreview: initialVideoPreview,
allowedFileExtensions : ['mp4'],
overwriteInitial: true,
maxFileSize: 20000,
maxFilesNum: 1,
allowedFileTypes: ['video'],
slugCallback: function(filename) {
return filename.replace('(', '_').replace(']', '_');
}
}).on("fileuploaded", function (event, data, previewId, index) {
$('input[name=wv_link]').val(data.response.attachment);
}).on("fileclear",function(event, data, msg){
$('input[name=wv_link]').val("");
}).on("filecleared",function(event, data, msg){
$('input[name=wv_link]').val("");
}).on('filebatchuploadcomplete', function(event, preview, config, tags, extraData) {
console.log('File Batch Uploaded', preview, config, tags, extraData);
}).on('filebatchselected', function (event, files){
$wvLinkInput.fileinput('upload');
}).on('fileuploaderror', function(event, data) {
var message = data.jqXHR.responseJSON.message;
var retainErrorHistory = false; // whether to retain error history
$wvLinkInput.fileinput('showUserError', message, data, retainErrorHistory);
});
Server Code Example (PHP)
// example of a PHP server code that is called in `uploadUrl` above
// file-upload.php script
header('Content-Type: application/json'); // set json response headers
$outData = upload(); // a function to upload the bootstrap-fileinput files
echo json_encode($outData); // return json data
exit(); // terminate
// main upload function used above
// upload the bootstrap-fileinput files
// returns associative array
function upload() {
$preview = $config = $errors = [];}
$targetDir = '/webroot/uploads';
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
$fileBlob = 'fileBlob'; // the parameter name that stores the file blob
if (isset($_FILES[$fileBlob]) && isset($_POST['uploadToken'])) {
$token = $_POST['uploadToken']; // gets the upload token
if (!validateToken($token)) { // your access validation routine (not included)
return [
'error' => 'Access not allowed' // return access control error
];
}
$file = $_FILES[$fileBlob]['tmp_name']; // the path for the uploaded file chunk
$fileName = $_POST['fileName']; // you receive the file name as a separate post data
$fileSize = $_POST['fileSize']; // you receive the file size as a separate post data
$fileId = $_POST['fileId']; // you receive the file identifier as a separate post data
$index = $_POST['chunkIndex']; // the current file chunk index
$totalChunks = $_POST['chunkCount']; // the total number of chunks for this file
$targetFile = $targetDir.'/'.$fileName; // your target file path
if ($totalChunks > 1) { // create chunk files only if chunks are greater than 1
$targetFile .= '_' . str_pad($index, 4, '0', STR_PAD_LEFT);
}
$thumbnail = 'unknown.jpg';
if(move_uploaded_file($file, $targetFile)) {
// get list of all chunks uploaded so far to server
$chunks = glob("{$targetDir}/{$fileName}_*");
// check uploaded chunks so far (do not combine files if only one chunk received)
$allChunksUploaded = $totalChunks > 1 && count($chunks) == $totalChunks;
if ($allChunksUploaded) { // all chunks were uploaded
$outFile = $targetDir.'/'.$fileName;
// combines all file chunks to one file
combineChunks($chunks, $outFile);
}
// if you wish to generate a thumbnail image for the file
$targetUrl = getThumbnailUrl($path, $fileName);
// separate link for the full blown image file
$zoomUrl = 'http://localhost/uploads/' . $fileName;
return [
'chunkIndex' => $index, // the chunk index processed
'initialPreview' => $targetUrl, // the thumbnail preview data (e.g. image)
'initialPreviewConfig' => [
[
'type' => 'image', // check previewTypes (set it to 'other' if you want no content preview)
'caption' => $fileName, // caption
'key' => $fileId, // keys for deleting/reorganizing preview
'fileId' => $fileId, // file identifier
'size' => $fileSize, // file size
'zoomData' => $zoomUrl, // separate larger zoom data
]
],
'append' => true
];
} else {
return [
'error' => 'Error uploading chunk ' . $_POST['chunkIndex']
];
}
}
return [
'error' => 'No file found'
];
}
// combine all chunks
// no exception handling included here - you may wish to incorporate that
function combineChunks($chunks, $targetFile) {
// open target file handle
$handle = fopen($targetFile, 'a+');
foreach ($chunks as $file) {
fwrite($handle, file_get_contents($file));
}
// you may need to do some checks to see if file
// is matching the original (e.g. by comparing file size)
// after all are done delete the chunks
foreach ($chunks as $file) {
@unlink($file);
}
// close the file handle
fclose($handle);
}
// generate and fetch thumbnail for the file
function getThumbnailUrl($path, $fileName) {
// assuming this is an image file or video file
// generate a compressed smaller version of the file
// here and return the status
$sourceFile = $path . '/' . $fileName;
$targetFile = $path . '/thumbs/' . $fileName;
//
// generateThumbnail: method to generate thumbnail (not included)
// using $sourceFile and $targetFile
//
if (generateThumbnail($sourceFile, $targetFile) === true) {
return 'http://localhost/uploads/thumbs/' . $fileName;
} else {
return 'http://localhost/uploads/' . $fileName; // return the original file
}
}
自动上传:
.on('filebatchselected', function (event, files){
$wvLinkInput.fileinput('upload');
})
报错处理:
.on('fileuploaderror', function(event, data) {
var message = data.jqXHR.responseJSON.message;
var retainErrorHistory = false; // whether to retain error history
$wvLinkInput.fileinput('showUserError', message, data, retainErrorHistory);
});
该文展示了如何使用BootstrapFileInput插件进行视频文件的上传,包括设置语言、上传URL、预览、限制文件类型和大小等。在服务器端,使用PHP处理文件上传,验证权限,合并文件片段,并生成缩略图。同时,文中还提及了错误处理机制,如文件上传失败时的反馈。
8万+

被折叠的 条评论
为什么被折叠?



