通过ftp上传文件到指定服务器

本文展示了如何使用JSP页面和WebUploader库实现文件上传功能。通过JavaScript代码实现图片预览和删除,同时提供了后端Java代码处理上传请求,包括FTP连接、文件保存以及错误处理。文件上传后会被保存到指定的FTP服务器路径。

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

jsp页面上传部分代码

<script src="${ctxStatic}/js/newUpload.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var point_img = $("#activty_wechat_input").val();
if(point_img != "") {
var filelist = point_img.split(",");
$.each(filelist, function(k, v){
var string = "<li><p class=\"imgWrap\"><img src=\"" + v + "\"></p><div title=\"删除\" class=\"cancel\"></div></li>";
$(".imglist").append(string);
});
}
 
//删除图片调整路径
$(document).on("click",".imglist .cancel", function(){
var pointImg = $("#activty_wechat_input").val();
$(this).parent("li").remove();
var newSrc = "", imgsrc = $(this).parent("li").find("img").attr("src");
if(pointImg.indexOf(imgsrc + ",") != -1) {
newSrc = pointImg.replace(imgsrc + ",", "");
} else {
newSrc = pointImg.replace(imgsrc, "");
}
  if (newSrc.charAt(newSrc.length - 1) == ',') {
  newSrc = newSrc.substring(0, newSrc.length - 1);
  }
$("#activty_wechat_input").val(newSrc);    
$("#packageImg").val(newSrc);
});
});
</script>


<body>
<form:form id="inputForm" modelAttribute="activtyWechat" action="${ctx}/comprehensive/activtyWechat/save" method="post" class="form-horizontal">
<form:hidden path="id"/>
<input id="func" type="hidden" value="activtyImg">
        <input id="func_no" type="hidden" value="img">
        <input id="store_no" name="storeNo" type="hidden" value="activtyImg${entry.activtyId}">

<div class="control-group">
<label class="control-label">图片:</label>
<div class="controls">
<style type="text/css">
.imglist li {
   width: 110px;
   height: 110px;
   background: url(/JGGFrame/static/images/webuploader/bg.png) no-repeat;
   text-align: center;
   margin: 0 8px 20px 0;
   position: relative;
   display: inline;
   float: left;
   overflow: hidden;
   font-size: 12px;
   }
   
   .imglist li p.imgWrap {
   position: relative;
   z-index: 2;
   line-height: 110px;
   vertical-align: middle;
   overflow: hidden;
   width: 110px;
   height: 110px;

   -webkit-transform-origin: 50% 50%;
   -moz-transform-origin: 50% 50%;
   -o-transform-origin: 50% 50%;
   -ms-transform-origin: 50% 50%;
   transform-origin: 50% 50%;

   -webit-transition: 200ms ease-out;
   -moz-transition: 200ms ease-out;
   -o-transition: 200ms ease-out;
   -ms-transition: 200ms ease-out;
   transition: 200ms ease-out;
}

.imglist li img {
   width: 100%;
   height: 100%;
}

.imglist .cancel {
width:20px;
height:20px;
background:url(/JGGFrame/static/images/webuploader/icons.png) no-repeat -48px -0.5px;
position: absolute;
right:0;
top:0;
cursor:pointer;
overflow:hidden;
z-index:10;
}
</style>


<ul class="imglist">
<input name="point_img" type="hidden" value="${entry.activtyBannerImgString}" id="activty_wechat_input" />
</ul>


</div>
</div>

<div class="control-group">
<input id="packageImg" name=activtyBannerImg value="${entry.activtyBannerImg}" type="hidden"/>
<input name="pointImg" id="packagesThumbnail" style="display: none" />
<label class="control-label">图片:</label>
<div class="controls">
           <div id="uploader">
               <div class="queueList">
<div id="dndArea" class="placeholder">
                       <div id="filePicker"></div>
                       <p>或将照片拖到这里,单次最多可选15张</p>
                   </div>
               </div>
               <div class="statusBar" style="display:none;">
                   <div class="progressBar">
                       <span class="text">0%</span>
                       <span class="percentage"></span>
                   </div><div class="info"></div>
                   <div class="btns">
                       <div id="filePicker2"></div><div class="uploadBtn">开始上传</div>
                   </div>
               </div>
           </div>
</div>
</div>
</form:form>
</body>


引用的js代码

(function( $ ){
    // 当domReady的时候开始初始化
    $(function() {
        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,


            //返回原图路径
            path = $("#packageImg").val(),
            
            //返回缩略图路径
            thumbnail_path = $("#packagesThumbnail").val(),
            
            //商家号
            store_no = $("#store_no").val(),
            
            //功能名称
            func = $("#func").val(),
            
            //功能代号
            func_no = $("#func_no").val(),


            // 优化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 不支持您的浏览器!');
            return;
        }
        // 实例化
        uploader = WebUploader.create({
            pick: {
                id: '#filePicker',
                label: '点击选择图片'
            },
            formData: {
                uid: 123,
                store_no : store_no,
                func : func,
                func_no : $("#func_no").val()
            },
            dnd: '#dndArea',
            paste: '#uploader',
            swf: '../../dist/Uploader.swf',
            chunked: false,
            chunkSize: 512 * 1024,
            threads:1,
            server: 'http://localhost:8080/JGGFrame/a/comprehensive/upload/ajaxFileUpload',
            auto: false,
            resize: true,
            accept: {
                title: 'image',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/gif, image/jpg, image/jpeg, image/bmp, image/png,'
            },


            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
            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: '继续添加'
        });


        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">删除</span>' +
                    '<span class="rotateRight">向右旋转</span>' +
                    '<span class="rotateLeft">向左旋转</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 = '文件大小超出';
                            break;


                        case 'interrupt':
                            text = '上传暂停';
                            break;


                        default:
                            text = '上传失败,请重试';
                            break;
                    }


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


            if ( file.getStatus() === 'invalid' ) {
                showError( file.statusText );
            } else {
                // @todo lazyload
                $wrap.text( '预览中' );
                uploader.makeThumb( file, function( error, src ) {
                    var img;


                    if ( error ) {
                        $wrap.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 = '选中' + fileCount + '张图片,共' +
                        WebUploader.formatSize( fileSize ) + '。';
            } else if ( state === 'confirm' ) {
                stats = uploader.getStats();
                if ( stats.uploadFailNum ) {
                    text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+
                        stats.uploadFailNum + '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                }


            } else {
                stats = uploader.getStats();
                text = '共' + fileCount + '张(' +
                        WebUploader.formatSize( fileSize )  +
                        '),已上传' + stats.successNum + '张';


                if ( stats.uploadFailNum ) {
                    text += ',失败' + stats.uploadFailNum + '张';
                }
            }


            $info.html( text );
        }


        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( '暂停上传' );
                    break;


                case 'paused':
                    $progress.show();
                    $upload.text( '继续上传' );
                    break;


                case 'confirm':
                    $progress.hide();
                    $( '#filePicker2' ).removeClass( 'element-invisible' );
                    $upload.text( '开始上传' );


                    stats = uploader.getStats();
                    if ( stats.successNum && !stats.uploadFailNum ) {
                        setState( 'finish' );
                        return;
                    }
                    break;
                case 'finish':
                    stats = uploader.getStats();
                    if ( stats.successNum ) {
                        alert( '上传成功' );
                    } else {
                        // 没有成功的图片,重设
                        state = 'done';
                        location.reload();
                    }
                    break;
            }


            updateStatus();
        }


        uploader.onUploadSuccess = function( file, response ) {
            if(response.body.error_code == '00000000') {
            path = $("#packageImg").val();
                path = response.body.original_pic + ',' + path;
                thumbnail_path = response.body.thumbnail_pic + ',' + thumbnail_path;
                $("#packageImg").val(path);
                //如果是添加,返回功能编号
            }
        };


        uploader.onUploadFinished = function() {
        //原图
        path = $("#packageImg").val();
            if (path.charAt(path.length - 1) == ',') {
                path = path.substring(0, path.length - 1);
            }
            $("#packageImg").val(path);
            //缩略图
            if (thumbnail_path.charAt(thumbnail_path.length - 1) == ',') {
            thumbnail_path = thumbnail_path.substring(0, thumbnail_path.length - 1);
            }
            $("#packagesThumbnail").val(thumbnail_path);
            
        };


        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.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 ) {
            alert( 'Eroor: ' + code );
        };


        $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() {
            alert( 'todo' );
        } );


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


后台代码

@RequestMapping(value = "ajaxFileUpload")
public @ResponseBody JSONObject uploadOne(HttpServletRequest request, HttpServletResponse response)throws Exception {
JSONObject jsonObject=new JSONObject();
jsonObject.put("head", "");
String store_no = request.getParameter("store_no");
String func = request.getParameter("func");
String func_no = request.getParameter("func_no");
String original_path = "";
String thumbnail_path = "";
if(StringUtils.isEmpty(store_no)){
original_path = "newJGGFrame/originalpic/wechar/"+func+"/"+func_no;
thumbnail_path = "newJGGFrame/thumbnail/wechar/"+func+"/"+func_no;
}else{
original_path = "newJGGFrame/originalpic/wechar/"+func+"/"+store_no+"/"+func_no;
thumbnail_path = "newJGGFrame/thumbnail/wechar/"+func+"/"+store_no+"/"+func_no;
}
Map json_map = ImageUtil.picturenNewUpload(thumbnail_path, original_path, request,url, port, user, pwd, 200,200);
json_map.put("error_code", "00000000");
    json_map.put("error_text", "交易成功");
    json_map.put("func_no", func_no);
  jsonObject.put("body", json_map);
  return jsonObject;
}


/**

     * 
     * @param thumbnail_path 缩略图存储路径
     * @param original_path  原图存储路径
     * @param request 请求
     * @param url ftp连接地址
     * @param port ftp端口号
     * @param user ftp连接用户名
     * @param pwd ftp连接密码
     * @param w 缩略图处理宽
     * @param h 缩略图处理高
     * @return Map 包含 state(0:图片上传失败 1:图片上传成功) thumbnail_pic(缩略图路径) original_pic(原图路径)
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
public static Map picturenNewUpload(String thumbnail_path,String original_path, HttpServletRequest request,String url,int port,String user,String pwd,int w,int h)
throws Exception{
         Map returnMap = new HashMap<>();
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    // 判断 request 是否有文件上传,即多部分请求
    if (multipartResolver.isMultipart(request)) {
    // 转换成多部分request
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    boolean isSuccessOrNot = FTpUpLoad.ftpConnect(url, port, user, pwd);
    // 取得request中的所有文件名
    Iterator<String> iter = multiRequest.getFileNames();
    String original_pic = "";              //头像图片(原)
    String thumbnail_pic = "";         //套餐缩略图
    List<String> fileList = new ArrayList<>();
    while (iter.hasNext()) {
    // 记录上传过程起始时的时间,用来计算上传时间
    int pre = (int) System.currentTimeMillis();
    // 取得上传文件
    MultipartFile file = multiRequest.getFile(iter.next());
    if (file.getSize() > 0) {
    InputStream input = file.getInputStream();
                   if(!isSuccessOrNot){
                   returnMap.put("state", "0");
                   return returnMap;
                   }else{                  
                   String original_fileName = FTpUpLoad.uploadFile(input, original_path,file.getOriginalFilename());
                   //ftp上传成功,返回文件名
                   if(!(original_fileName.equals("1")||original_fileName.equals("2"))){
                   returnMap.put("state", "1");
                   original_pic += original_path+"/"+original_fileName+",";
                  //目录创建失败
                        }else if(original_fileName.equals("1")){
                           returnMap.put("state", "0");
                           FTpUpLoad.closeCon();
                     return returnMap;
                     //上传失败
                        }else if(original_fileName.equals("2")){
                       returnMap.put("state", "0");
                       FTpUpLoad.closeCon();
                     return returnMap;
                        }
                   //所略图本地临时过渡存放路径
                   String multipartFileName = file.getOriginalFilename();
                   String cuufile_path =temp_path;
                   cuufile_path = cuufile_path + Md5_32bit(multipartFileName)+".jpg";
                   File currfile = new File(cuufile_path);
                   if(!currfile.exists()){
                       file.transferTo(currfile);//不存在写文件 
                   }
                   if(StringUtils.isNotEmpty(thumbnail_path)){
                       //按照要求规格进行缩略
                   ImageUtil.compressImage(currfile.getPath(), currfile.getPath(), w, h);
                       //获取文件流
                       InputStream temp_input =  new FileInputStream(currfile);
                       //Ftp上传
                       String thumbnail_filename = FTpUpLoad.uploadFile(temp_input, thumbnail_path, file.getOriginalFilename());
                       //ftp上传成功,返回文件名
                       if(!(thumbnail_filename.equals("1") || thumbnail_filename.equals("2"))){
                       returnMap.put("state", "1");
                       thumbnail_pic += thumbnail_path+"/"+thumbnail_filename+",";
                       fileList.add(currfile.getPath());
                    //目录创建失败
                            }else if(thumbnail_filename.equals("1")){
                           returnMap.put("state", "0");
                           FTpUpLoad.closeCon();
                         return returnMap;
                            //上传失败
                            }else if(thumbnail_filename.equals("2")){
                           returnMap.put("state", "0");
                           FTpUpLoad.closeCon();
                         return returnMap;
                            }
                   }

                   }
    }
    }
    // 出去拼接字符串的最后的逗号分隔符
    if (!original_pic.isEmpty()) {
    returnMap.put("original_pic",original_pic.substring(0, original_pic.length() - 1));
    }
    // 出去拼接字符串的最后的逗号分隔符
    if (!thumbnail_pic.isEmpty()) {
    returnMap.put("thumbnail_pic",thumbnail_pic.substring(0,thumbnail_pic.length() - 1));
    }
    for (String filePath : fileList) {
    DeleteFolder(filePath);
    }
    //FTpUpLoad.closeCon();
    }
return returnMap;

    }


/**

* @param addr 地址
* @param port  端口号
* @param username   用户名
* @param password  密码
* @param input  InputStream
* @param path  相对文件目录
* @param filename 文件名
* @return String
* @throws Exception
*/
public static boolean ftpConnect(String addr, int port, String username,String password) throws Exception {
boolean result = false;
int reply;
ftp.connect(addr, port);
result = ftp.login(username, password);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
} else {
result = true;
}
return result;
}


/**

* @param input 图片流
* @param path 上传的图片FTP路径
* @param filename 图片名
* @return
* @throws Exception
*/
public static String uploadFile(InputStream input, String path,String filename) throws Exception {
boolean flag = mkdirs(ftp, path);
if (!flag) {
return "1";
}
filename = sdf.format(new Date()) + MD5.Md5(filename) + ".jpg";
boolean state = ftp.storeFile(filename, input);
input.close();
            boolean a= ftp.changeWorkingDirectory("/");
if (state) {
return filename;
} else {
return "2";
}
}


/** 
     * * 将图片按照指定的图片尺寸压缩 
     * @param srcImgPath :源图片路径 
     * @param outImgPath  :输出的压缩图片的路径  
     * @param new_w :压缩后的图片宽 
     * @param new_h :压缩后的图片高 
     */  
    public static void compressImage(String srcImgPath,String outImgPath,int new_w, int new_h) {  
        BufferedImage src = InputImage(srcImgPath);  
         disposeImage(src,outImgPath,new_w, new_h);  
    }


 /**
* 根据路径删除指定的目录或文件,无论存在与否
* @param sPath 要删除的目录或文件
* @return 删除成功返回 true,否则返回 false。
*/
public static boolean DeleteFolder(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(sPath);
} else { // 为目录时调用删除目录方法
return deleteDirectory(sPath);
}
}
}


/**
* 删除单个文件
* @param sPath 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}


/**
* 删除目录(文件夹)以及目录下的文件
* @param sPath  被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String sPath) {
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} // 删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag)
return false;
// 删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}


/**  
     * 图片文件读取  
     * @param srcImgPath  
     * @return  
     */  
    private static BufferedImage InputImage(String srcImgPath) {  
        BufferedImage srcImage = null;  
        try {  
            FileInputStream in = new FileInputStream(srcImgPath);  
            srcImage = javax.imageio.ImageIO.read(in); 
            in.close();
        } catch (IOException e) {  
            System.out.println("读取图片文件出错!" + e.getMessage());  
            e.printStackTrace();  
        }finally{
       
        }
        return srcImage;  
    }


/**  
     * 处理图片 
     * @param src  
     * @param outImgPath  
     * @param new_w  
     * @param new_h  
     */  
    private synchronized static void disposeImage(BufferedImage src,String outImgPath,int new_w, int new_h) {  
        int old_w = src.getWidth();  // 得到图片  
        int old_h = src.getHeight();  // 得到源图宽  
        BufferedImage newImg = null;    // 得到源图长  
        switch (src.getType()) {   // 判断输入图片的类型  
        case 13:  
            // png,gifnewImg = new BufferedImage(new_w, new_h,  
            // BufferedImage.TYPE_4BYTE_ABGR);  
            break;  
        default:  
            newImg = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);  
            break;  
        }  
        Graphics2D g = newImg.createGraphics();  
        g.drawImage(src, 0, 0, old_w, old_h, null);  // 从原图上取颜色绘制新图  
        g.dispose();  
        // 根据图片尺寸压缩比得到新图的尺寸  
        newImg.getGraphics().drawImage(src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0,null);  
        // 调用方法输出图片文件  
        OutImage(newImg, outImgPath);
    }


/** 
     * 将图片文件输出到指定的路径,并可设定压缩质量  
     * @param outImgPath  
     * @param newImg  
     * @param per 
     */  
    private static void  OutImage( BufferedImage newImg,String outImgPath) {  
        // 判断输出的文件夹路径是否存在,不存在则创建  
        File file = new File(outImgPath);  
        if (!file.getParentFile().exists()) {  
            file.getParentFile().mkdirs();  
        }// 输出到文件流  
        try {  
            ImageIO.write(newImg,outImgPath.substring(outImgPath.lastIndexOf(".") + 1),new File(outImgPath));  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    ByteArrayOutputStream bs = new ByteArrayOutputStream(); 
    ImageOutputStream imOut;
try {
imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(newImg, "jpg", imOut);
} catch (IOException e) {
e.printStackTrace();
}
    return ;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值