记一次WebUploader的使用

本文介绍了一个基于百度开源的WebUploader组件实现的文件上传系统。该系统支持批量上传、上传进度展示及文件预览等功能,并详细展示了如何配置上传组件、处理上传逻辑及与后台交互的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WebUploader是百度开源的一个文件上传组件,因为其操作简洁大方,就在项目中使用了,记录一下。
效果是这样子:
这里写图片描述
这个样子是默认的效果。

这里写图片描述
这个是选择上传的图片,可以批量,选择后可以删除和添加更多。

这里写图片描述
这个是上传过程显示的效果。

<div id="container">
   <!--头部,相册选择和格式选择-->
   <div id="uploader">
       <div class="queueList">
           <div id="dndArea" class="placeholder">
               <div id="filePicker"></div>
               <p><s:text name="resource.upload.tip"/></p>
           </div>
       </div>
       <div class="statusBar" style="display:none;">
           <div class="progress">
               <span class="text">0%</span>
               <span class="percentage"></span>
           </div>
           <div class="info"></div>
           <div class="btns">
               <div id="filePicker2"></div>
               <div class="uploadBtn"><s:text name="resource.starttoupload"></s:text></div>
           </div>
       </div>
   </div>
</div>

js部分代码,下面这段代码是webuploader官方的示例代码uploader.js做的修改:

(function( $ ){
    // 当domReady的时候开始初始化
    $(function() {
        var filePerSize = [];//每个文件大小
        var fileName = [];
        var fileSize = 0;

        var $wrap = $('#uploader'),

            // 图片容器
            $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),

            // 状态栏,包括进度和控制按钮
            $statusBar = $wrap.find('.statusBar'),

            // 文件总体选择信息。
            $info = $statusBar.find('.info'),

            // 上传按钮
            $upload = $wrap.find('.uploadBtn'),

            // 没选择文件之前的内容。
            $placeHolder = $wrap.find('.placeholder'),

            $progress = $statusBar.find('.progress').hide(),

            // 添加的文件数量
            fileCount = 0,

            // 添加的文件总大小
            fileSize = 0,

            // 优化retina, 在retina下这个值是2
            ratio = window.devicePixelRatio || 1,

            // 缩略图大小
            thumbnailWidth = 110 * ratio,
            thumbnailHeight = 110 * ratio,

            // 可能有pedding, ready, uploading, confirm, done.
            state = 'pedding',

            // 所有文件的进度信息,key为file id
            percentages = {},
            // 判断浏览器是否支持图片的base64
            isSupportBase64 = ( function() {
                var data = new Image();
                var support = true;
                data.onload = data.onerror = function() {
                    if( this.width != 1 || this.height != 1 ) {
                        support = false;
                    }
                }
                data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
                return support;
            })(),

            // 检测是否已经安装flash,检测flash的版本
            flashVersion = ( function() {
                var version;
                try {
                    version = navigator.plugins[ 'Shockwave Flash' ];
                    version = version.description;
                } catch ( ex ) {
                    try {
                        version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
                                .GetVariable('$version');
                    } catch ( ex2 ) {
                        version = '0.0';
                    }
                }
                version = version.match( /\d+/g );
                return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
            } )(),

            supportTransition = (function(){
                var s = document.createElement('p').style,
                    r = 'transition' in s ||
                            'WebkitTransition' in s ||
                            'MozTransition' in s ||
                            'msTransition' in s ||
                            'OTransition' in s;
                s = null;
                return r;
            })(),

            // WebUploader实例
            uploader;

        if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {
            // flash 安装了但是版本过低。
            if (flashVersion) {
                (function(container) {
                    window['expressinstallcallback'] = function( state ) {
                        switch(state) {
                            case 'Download.Cancelled':
                                //alert('您取消了更新!')
                                break;

                            case 'Download.Failed':
                                //alert('安装失败')
                                break;

                            default:
                                //alert('安装已成功,请刷新!');
                                break;
                        }
                        delete window['expressinstallcallback'];
                    };

                    var swf = './expressInstall.swf';
                    // insert flash object
                    var html = '<object type="application/' +
                            'x-shockwave-flash" data="' +  swf + '" ';

                    if (WebUploader.browser.ie) {
                        html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                    }

                    html += 'width="100%" height="100%" style="outline:0">'  +
                        '<param name="movie" value="' + swf + '" />' +
                        '<param name="wmode" value="transparent" />' +
                        '<param name="allowscriptaccess" value="always" />' +
                    '</object>';

                    container.html(html);
                })($wrap);

            // 压根就没有安转。
            } else {
                $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
            }

            return;
        } else if (!WebUploader.Uploader.support()) {
            alert( 'Web Uploader not support your browser!');
            return;
        }

        // 实例化
        uploader = WebUploader.create({
            pick: {
                id: '#filePicker',
                name: 'multiFile',
                label: 'Click To Select'
            },
            formData: {
                "status": "multi",
                "contentsDto.contentsId": "xxxx",
                "uploadNum": "xxxx",
                "existFlg": "false",
            },
            dnd: '#dndArea',
            paste: '#uploader',
            method: 'POST',
            swf: '../../dist/Uploader.swf',
            chunked: false,
            chunkSize: 512 * 1024,
            chunkRetry:false,
            server: 'resource/upload.action?resourcetype=hd',
            fileVal:'multiFile',
            resize: false,
            // runtimeOrder: 'flash',

            /* accept: {
                title: 'Images',
                extensions: 'gif,jpg,bmp,png,m2v',
                mimeTypes: 'image/*,video/mpeg',
            }, */

            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
            disableGlobalDnd: true,
            fileNumLimit: 300,
            fileSizeLimit: 200 * 1024 * 1024,    // 200 M
            fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
        });

        // 拖拽时不接受 js, txt 文件。
        uploader.on('dndAccept', function( items ) {
            var denied = false,
                len = items.length,
                i = 0,
                // 修改js类型
                unAllowed = 'text/plain;application/javascript ';

            for ( ; i < len; i++ ) {
                // 如果在列表里面
                if ( ~unAllowed.indexOf( items[ i ].type ) ) {
                    denied = true;
                    break;
                }
            }
            return !denied;
        });

        //点击按钮弹出选择框
        /*uploader.on('dialogOpen', function() {
            console.log('here');
        });*/

        // 添加"添加文件"的按钮,
        uploader.addButton({
            id: '#filePicker2',
            label: '<s:text name="resource.addmore"></s:text>'
        });

        uploader.on('ready', function() {
            window.uploader = uploader;
        });

        // 当有文件添加进来时执行,负责view的创建
        function addFile( file ) {
            var $li = $( '<li id="' + file.id + '">' +
                    '<p class="title">' + file.name + '</p>' +
                    '<p class="imgWrap"></p>'+
                    '<p class="progress"><span></span></p>' +
                    '</li>' ),

                $btns = $('<div class="file-panel">' +
                    '<span class="cancel"><s:text name="resource.delete"></s:text></span>' +
                    '<span class="rotateRight"><s:text name="resource.rotateToRight"></s:text></span>' +
                    '<span class="rotateLeft"><s:text name="resource.rotateToLeft"></s:text></span></div>').appendTo( $li ),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find( 'p.imgWrap' ),
                $info = $('<p class="error"></p>'),

                showError = function( code ) {
                    switch( code ) {
                        case 'exceed_size':
                            text = '<s:text name="resource.exceedSize"></s:text>';
                            break;

                        case 'interrupt':
                            text = '<s:text name="resource.pauseupload"></s:text>';
                            break;

                        default:
                            text = '<s:text name="resource.uploadfailed"></s:text>';
                            break;
                    }

                    $info.text( text ).appendTo( $li );
                };

            if ( file.getStatus() === 'invalid' ) {
                showError( file.statusText );
            } else {
                // @todo lazyload
                $wrap.text( '<s:text name="resource.onPreview"></s:text>' );
                uploader.makeThumb( file, function( error, src ) {
                    var img;

                    if ( error ) {
                        $wrap.text( '<s:text name="resource.unablePreview"></s:text>' );
                        return;
                    }

                    if( isSupportBase64 ) {
                        img = $('<img src="'+src+'">');
                        $wrap.empty().append( img );
                    } else {
                        /*$.ajax('../../server/preview.php', {
                            method: 'POST',
                            data: src,
                            dataType:'json'
                        }).done(function( response ) {
                            if (response.result) {
                                img = $('<img src="'+response.result+'">');
                                $wrap.empty().append( img );
                            } else {
                                $wrap.text("预览出错");
                            }
                        });*/
                    }
                }, thumbnailWidth, thumbnailHeight );

                percentages[ file.id ] = [ file.size, 0 ];
                file.rotation = 0;
            }

            file.on('statuschange', function( cur, prev ) {
                if ( prev === 'progress' ) {
                    $prgress.hide().width(0);
                } else if ( prev === 'queued' ) {
                    $li.off( 'mouseenter mouseleave' );
                    $btns.remove();
                }
                // 成功
                if (cur === 'error' || cur === 'invalid') {
                    console.log( file.statusText );
                    showError( file.statusText );
                    percentages[ file.id ][ 1 ] = 1;
                } else if ( cur === 'interrupt' ) {
                    showError( 'interrupt' );
                } else if ( cur === 'queued' ) {
                    $info.remove();
                    $prgress.css('display', 'block');
                    percentages[ file.id ][ 1 ] = 0;
                } else if ( cur === 'progress' ) {
                    $info.remove();
                    $prgress.css('display', 'block');
                } else if ( cur === 'complete' ) {
                    $prgress.hide().width(0);
                    $li.append('<span class="success"></span>');
                }

                $li.removeClass('state-' + prev).addClass('state-' + cur);
            });

            $li.on('mouseenter', function() {
                $btns.stop().animate({height: 30});
            });

            $li.on('mouseleave', function() {
                $btns.stop().animate({height: 0});
            });

            $btns.on('click', 'span', function() {
                var index = $(this).index(),
                    deg;
                switch (index) {
                    case 0:
                        uploader.removeFile( file );
                        return;

                    case 1:
                        file.rotation += 90;
                        break;

                    case 2:
                        file.rotation -= 90;
                        break;
                }
                if (supportTransition) {
                    deg = 'rotate(' + file.rotation + 'deg)';
                    $wrap.css({
                        '-webkit-transform': deg,
                        '-mos-transform': deg,
                        '-o-transform': deg,
                        'transform': deg
                    });
                } else {
                    $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
                }
            });
            $li.appendTo($queue);
        }

        // 负责view的销毁
        function removeFile( file ) {
            var $li = $('#'+file.id);

            delete percentages[ file.id ];
            updateTotalProgress();
            $li.off().find('.file-panel').off().end().remove();
        }

        function updateTotalProgress() {
            var loaded = 0,
                total = 0,
                spans = $progress.children(),
                percent;
            $.each( percentages, function( k, v ) {
                total += v[ 0 ];
                loaded += v[ 0 ] * v[ 1 ];
            } );

            percent = total ? loaded / total : 0;
            spans.eq( 0 ).text(Math.round( percent * 100 ) + '%');
            spans.eq( 1 ).css('width', Math.round( percent * 100 ) + '%');
            updateStatus();
        }

        function updateStatus() {
            var text = '', stats;
            if ( state === 'ready' ) {
                text = '<s:text name="resource.selected"></s:text>' + fileCount + ', <s:text name="resource.totalSize"></s:text>' +
                        WebUploader.formatSize(fileSize);
            } else if ( state === 'confirm' ) {
                stats = uploader.getStats();
                if ( stats.uploadFailNum ) {
                    text = '<s:text name="resource.uploaded"></s:text>' + stats.successNum+ ', <s:text name="resource.failed"></s:text>'+
                        stats.uploadFailNum + ', <a class="retry" href="#" style="color:red;">' + '<s:text name="resource.retry"></s:text>'+'</a>&nbsp;<s:text name="resource.or"></s:text><a class="ignore" href="#" style="color:blue;">&nbsp;<s:text name="resource.ignore"></s:text></a>'
                }
            } else {
                stats = uploader.getStats();
                text = '<s:text name="resource.total"></s:text>' + fileCount + '(' +
                        WebUploader.formatSize( fileSize )  +
                        '), <s:text name="resource.uploaded"></s:text>:' + stats.successNum;

                if ( stats.uploadFailNum ) {
                    text += ', <s:text name="resource.failed"></s:text>:' + stats.uploadFailNum;
                }
            }
            $info.html(text);
        }

        /*关闭上传框窗口后恢复上传框初始状态*/
        function closeUploader() {        
            // 移除所有缩略图并将上传文件移出上传序列
            for (var i = 0; i < uploader.getFiles().length; i++) {
                // 将图片从上传序列移除
                uploader.removeFile(uploader.getFiles()[i]);
                // 将图片从缩略图容器移除
                var $li = $('#' + uploader.getFiles()[i].id);
                $li.off().remove();
            }
            setState('pedding');
            // 重置文件总个数和总大小
            fileCount = 0;
            fileSize = 0;
            // 重置uploader,目前只重置了文件队列
            uploader.reset();
            // 更新状态等,重新计算文件总个数和总大小
            updateStatus();
        }

        function setState( val ) {
            var file, stats;
            if ( val === state ) {
                return;
            }
            $upload.removeClass( 'state-' + state );
            $upload.addClass( 'state-' + val );
            state = val;
            switch (state) {
                case 'pedding':
                    $placeHolder.removeClass( 'element-invisible' );
                    $queue.hide();
                    $statusBar.addClass( 'element-invisible' );
                    uploader.refresh();
                    break;

                case 'ready':
                    $placeHolder.addClass( 'element-invisible' );
                    $( '#filePicker2' ).removeClass( 'element-invisible');
                    $queue.show();
                    $statusBar.removeClass('element-invisible');
                    uploader.refresh();
                    break;

                case 'uploading':
                    $( '#filePicker2' ).addClass( 'element-invisible' );
                    $progress.show();
                    $upload.text( '<s:text name="resource.pauseupload"></s:text>' );
                    var fileArray1 = uploader.getFiles();
                    var fileNames = [];
                    fileSize = 0;
                    for(var i=0; i<fileArray1.length; i++) {
                        fileNames.push(fileArray1[i].name);
                        fileSize += fileArray1[i].size;
                        filePerSize.push(fileArray1[i].size);
                        fileName.push(fileArray1[i].name);
                    }
                    $.extend(true, uploader.options.formData, {"fileSize": fileSize, "multiFileName": fileName, "filePerSize": filePerSize});
                    break;

                case 'paused':
                    $progress.show();
                    $upload.text('<s:text name="resource.continueupload"></s:text>');
                    break;

                case 'confirm':
                    $progress.hide();
                    $('#filePicker2').removeClass('element-invisible');
                    $upload.text('<s:text name="resource.starttoupload"></s:text>');

                    stats = uploader.getStats();
                    if (stats.successNum && !stats.uploadFailNum) {
                        setState('finish');
                        return;
                    }
                    break;
                case 'finish':
                    stats = uploader.getStats();
                    //alert(stats.successNum);
                    if (stats.successNum) {
                        if(flag) {
                            //alert('上传成功');
                            confirmBox("<s:text name='resource.tiptitle'></s:text>",
                                            "Upload Success",
                                            function(tag) {
                                                if (tag) {
                                                    var url = 'resource/uploadHd.jsp';
                                                    loadUrl(url);
                                                } else {
                                                    return;
                                                } 
                                            });
                                    $("#boxwhite a[name=f]").html("<s:text name="box.no"/>").hide(); 
                                    $("#boxwhite a[name=t]").html("<s:text name="box.sure"/>");
                        } else {
                            loadUrl('resource/uploadHd.jsp');
                        }
                        //刷新界面 
                        //setTimeout("loadUrl('resource/uploadHd.jsp')", 1000);
                    } else {
                        // 没有成功的图片,重设
                        state = 'done';
                        location.reload();
                    }
                    break;
            }
            updateStatus();
        }

        var flag = true;

        uploader.on("uploadAccept", function(object, ret){
            if(ret != null && ret != '') {
                var data = JSON.parse(ret._raw);
                if(data != null && data != '') {
                    if(data.resultCode == '1' || data.resultCode == '2') {
                        var tip = '';
                        if(data.resultCode == '1') {
                            tip = "<s:text name='resource.fileExists'></s:text>";
                        }else {
                            tip = "<s:text name='resource.fileTypeError'></s:text>" + data.message;
                        }
                        confirmBox("<s:text name='resource.tiptitle'></s:text>",
                                tip,
                                function(tag) {
                                    if (tag) {
                                        flag = false;
                                        updateStatus();
                                        var url = 'resource/uploadHd.jsp';
                                        loadUrl(url);
                                    } else {
                                        return;
                                    } 
                                });
                        $("#boxwhite a[name=f]").html("<s:text name="box.no"/>").hide(); 
                        $("#boxwhite a[name=t]").html("<s:text name="box.sure"/>");
                    } else {
                        flag = true;
                    }
                }
            }
        });

        uploader.onUploadProgress = function(file, percentage) {
            var $li = $('#'+file.id),
                $percent = $li.find('.progress span');

            $percent.css( 'width', percentage * 100 + '%' );
            percentages[ file.id ][ 1 ] = percentage;
            updateTotalProgress();
        };

        uploader.on("uploadError", function(file, reason){
            alert("uploadError");
        });

        uploader.onFileQueued = function(file) {
            fileCount++;
            fileSize += file.size;
            if (fileCount === 1) {
                $placeHolder.addClass('element-invisible');
                $statusBar.show();
            }

            addFile(file);
            setState('ready');
            updateTotalProgress();
        };

        /**
         * 移出队列
         */
        uploader.onFileDequeued = function( file ) {
            fileCount--;
            fileSize -= file.size;
            if ( !fileCount ) {
                setState('pedding');
            }
            removeFile(file);
            updateTotalProgress();
        };

        uploader.on('all', function(type) {
            var stats;
            switch(type) {
                case 'uploadFinished':
                    setState('confirm');
                    break;

                case 'startUpload':
                    setState('uploading');
                    break;

                case 'stopUpload':
                    setState('paused');
                    break;
            }
        });


        uploader.onError = function( code ) {
            if (type=="Q_TYPE_DENIED"){
                //dialogMsg("myModal","messageP","请上传JPG、PNG格式文件");
            }else if(type=="F_EXCEED_SIZE"){
                //dialogMsg("myModal","messageP","文件大小不能超过8M");
            }
            uploader.reset();
            fileSize = 0;
            fileName = [];
            filePerSize = [];
        }; 

        /**
         * 点击上传按钮
         */
        $upload.on('click', function() {
            if ( $(this).hasClass( 'disabled' ) ) {
                return false;
            }
            if (state === 'ready') {
                uploader.upload();
            } else if (state === 'paused') {
                uploader.upload();
            } else if (state === 'uploading') {
                uploader.stop();
            }
        });

        /**
         * 点击重试按钮
         */
        $info.on( 'click', '.retry', function() {
            uploader.retry();
        } );

        /**
         * 点击忽略按钮
         */
        $info.on( 'click', '.ignore', function() {
            //执行忽略动作,把图片清除
            closeUploader();
        });

        $upload.addClass( 'state-' + state );
        updateTotalProgress();
    });
})( jQuery );

使用Action接收时,可以这么写:

//多文件上传的文件对象,多文件是一个一个文件上传,所以multiFile是当前正在上传的文件对象
private File multiFile;
//多文件上传文件对象的名称,当前正在上传的文件名
private String multiFileFileName;
//所有文件的总大小
private String fileSize;
//文件名列表
private String[] multiFileName;
//每个文件的大小
private String[] filePerSize;
public void setMultiFile(File multiFile) {
        this.multiFile = multiFile;
}

public File getMultiFile() {
    return multiFile;
}

public void setMultiFileFileName(String multiFileFileName) {
    this.multiFileFileName = multiFileFileName;
}

public void setFileSize(String fileSize) {
    this.fileSize = fileSize;
}

public void setMultiFileName(String[] multiFileName) {
    this.multiFileName = multiFileName;
}

public void setFilePerSize(String[] filePerSize) {
    this.filePerSize = filePerSize;
}
public void uploadFile() {
    String physicPath = Constant.AD_RESOURCE_BASE_DIR;
    String subPath = "";
    int resolution = -1;
    String type = request.getParameter("resourcetype");
    if(StringUtils.isNotBlank(type)) {
        if(Constant.RESOURCE_TYPE_HD.equals(type)) {
            subPath = Constant.AD_RESOURCE_HD_DIR;
            resolution = 1;
        } else if(Constant.RESOURCE_TYPE_SD.equals(type)) {
            subPath = Constant.AD_RESOURCE_SD_DIR;
            resolution = 0;
        }
    }
    File fdir = new File(physicPath+"/"+subPath);
    if(!fdir.exists()) {
        fdir.mkdirs();
    }
    String resPath = "/" + subPath + "/" + multiFileFileName;
    String path = physicPath + resPath;//文件路径
    PrintWriter out = null;
    try {
        out = response.getWriter();
    } catch (IOException e) {
        log.error(e);
    }
    if(!isValidResource(multiFileFileName.substring(multiFileFileName.lastIndexOf(".") + 1))) {
        ResultJson resultJson = new ResultJson();
        resultJson.setResultCode("2");
        resultJson.setMessage(multiFileFileName);
        out.print(JsonUtil.toJsonString(resultJson));
        return;
    }
    try {
        File file = this.getMultiFile();
        //判断文件是否已经存在,不存在则存,否则不存
        String savePath = path.substring(path.lastIndexOf("/" + Constant.AD_RESOURCE_STORE_BASE_DIR));
        boolean isExists = adResourceService.queryFile(savePath);//linux下图片名区分大小写
        log.info("isExist=" + isExists);
        if(isExists) {
            ResultJson resultJson = new ResultJson();
            resultJson.setResultCode("1");
            resultJson.setMessage("same name file exists!");
            response.getWriter().print(JsonUtil.toJsonString(resultJson));
            return;
        } else {
            ResultJson resultJson = new ResultJson();
            resultJson.setResultCode("0");
            resultJson.setMessage("ok");
            response.getWriter().print(JsonUtil.toJsonString(resultJson));
        }
        FileUtil.randomAccessFile(path, file);
        log.info("upload finish....");
        //insert into db.
        File f = new File(path);
        //1:bmp;2:jpg;3:gif;4:png;5:mpg;6:m2v
        log.info("f.exists()=" + f.exists());
        if(f.exists()) {
            String fname = f.getName();
            log.info("filename=" + fname);
            String fsuffix = fname.substring(fname.lastIndexOf(".") + 1);
            if(fname.endsWith(".bmp") || fname.endsWith(".BMP") || fname.endsWith(".jpg") || fname.endsWith(".JPG")
                    || fname.endsWith(".gif") || fname.endsWith(".GIF") || fname.endsWith(".png") || fname.endsWith(".PNG")) {

                BufferedImage bimg = ImageIO.read(f);
                int picWidth = bimg.getWidth();
                int picHeight = bimg.getHeight();
                int picType = 0;
                switch (fsuffix.toLowerCase()) {
                case Constant.IMG_FORMAT_BMP:
                    picType = 1;
                    break;
                case Constant.IMG_FORMAT_JPG:
                    picType = 2;
                    break;
                case Constant.IMG_FORMAT_PNG:
                    picType = 4;
                    break;
                case Constant.IMG_FORMAT_GIF:
                    picType = 3;
                    break;
                }
                System.out.println("fileSize=" + file.length());
                log.info("fileSize=" + file.length());
                adResourceService.upload(resolution, resPath, picHeight, picWidth, (int)file.length(), picType, fsuffix);
            } else if(fname.endsWith(".mpg") || fname.endsWith(".MPG") || fname.endsWith(".m2v") || fname.endsWith(".M2V")) {
                //截取画像,获取分辨率
                //mpg , m2v,直接把文件路径存进去,在预览的时候动态生成帧画面
                int picType = 0;
                if(fname.endsWith(".mpg") || fname.endsWith(".MPG")) {
                    picType = 5;
                } else if(fname.endsWith(".m2v") || fname.endsWith(".M2V")) {
                    picType = 6;
                }

                boolean b = FFmpegUtil.transfer(path, path+".jpg");//在文件名后直接加后缀,然后存到数据库中
                if(b) {
                    File snapFile = new File(path+".jpg");
                    BufferedImage bimg = ImageIO.read(snapFile);
                    int picWidth = bimg.getWidth();
                    int picHeight = bimg.getHeight();
                    //update db.
                    adResourceService.uploadVideo(resolution, resPath, picHeight, picWidth, (int)file.length(), picType, fsuffix, resPath+".jpg");
                } else {
                    log.error("generate snapshot file failed from " + path);
                }
            } else {
                log.error("file type invalid, we delete it...");
                f.delete();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        log.error(e);
    }
}

实际场景中可以根据自己的需要进行修改。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值