Bootstrap File Input - 示例:自动上传报错处理

该文展示了如何使用BootstrapFileInput插件进行视频文件的上传,包括设置语言、上传URL、预览、限制文件类型和大小等。在服务器端,使用PHP处理文件上传,验证权限,合并文件片段,并生成缩略图。同时,文中还提及了错误处理机制,如文件上传失败时的反馈。

官网链接 

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);
});

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰哥技术分享

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值