Jsch upload (based on SFTP protocol)

Source: Internet
Author: User

 Public classFtpfileuploadextendsBasecontroller {PrivateChannelsftp SFTP =NULL; PrivateSession sshsession =NULL; PrivateChannel Channel =NULL; /*** Connection to SFTP server *@return     */     Public Booleanconnectftpserver (String IP) {Try{Jsch Jsch=NewJsch (); Sshsession=jsch.getsession (Const.user, IP, const.port);            Sshsession.setpassword (Const.password); Properties Sshconfig=NewProperties (); Sshconfig.put ("Stricthostkeychecking", "no");            Sshsession.setconfig (Sshconfig);            Sshsession.connect (); Channel= Sshsession.openchannel ("SFTP");            Channel.connect (); SFTP=(CHANNELSFTP) channel; return true; } Catch(Exception e) {e.printstacktrace (); return false; }    }             PublicMap<string, string>fileUpload (String pathName, httpservletrequest request) {/*** Store return information*/Map<String,String> map =NewHashmap<>(); /*** Processing uploads*/                if(!servletfileupload.ismultipartcontent (Request)) {Map.put ("Error", "Please select the file to upload!" "); returnmap; }                if(!commtool.checkstr (PathName)) {Map.put ("Error", "file directory name cannot be empty!" "); returnmap; }                /*** file directory hierarchy creation*/String LocalPath= PathName + "/"; if(!" Temp. Equals (PathName)) {SimpleDateFormat format=NewSimpleDateFormat ("Yyyy-mm-dd"); String Ymd= Format.format (NewDate ()); LocalPath+ = Ymd + "/"; }                /*** Maximum file size*/        LongMaxSize = 1000000000; /*** Upload*/Fileitemfactory Factory=Newdiskfileitemfactory (); Servletfileupload Upload=Newservletfileupload (Factory); Upload.setheaderencoding ("Utf-8"); List<?> items =NULL; Try {            //If the uploaded file is more than one, set the key flag            intFlag = 1; Items=upload.parserequest (Request); Iterator<?> iterator =Items.iterator ();  while(Iterator.hasnext ()) {Fileitem Item=(Fileitem) iterator.next (); String FileName=Item.getname (); if(!Item.isformfield ()) {                    //File Size Check                    if(Item.getsize () >maxSize) {Map.put ("ErrorInfo", "Upload file size exceeds limit!" "); returnmap; }                    /** Check extension*/String Fileext= Filename.substring (Filename.lastindexof (".") +1). toLowerCase (); //Move the workspace to the appropriate directorystring[] folders = Localpath.split ("/");  for(String folder:folders) {if(Folder.length () > 0) {                            Try{sftp.cd (folder); } Catch(sftpexception e) {Try{Sftp.mkdir (folder);                                SFTP.CD (folder); } Catch(sftpexception E1) {Map.put ("ErrorInfo", "Server side folder operation Error"); returnmap; }                            }                        }                    }                                        //Reset file nameString NewFileName = Ymdtools.currenttimestamp () + "." +Fileext; //Upload a file                    Try{sftp.put (Item.getinputstream (), newfilename); //address returned when reading from ExcelString Resultpath = Const.base_path + LocalPath +NewFileName; Map.put ("Eurl" +flag, Resultpath); Flag++; } Catch(Exception E1) {e1.printstacktrace (); Map.put ("ErrorInfo", "Write File Error"); }                    //file upload completed, working directory callback, so that other files upload                     for(inti=0; i<folders.length-1; i++) {                        Try{sftp.cd (".."); } Catch(sftpexception e) {map.put ("ErrorInfo", "folder callback error occurred"); returnmap; }                    }                }            }        } Catch(fileuploadexception e) {map.put ("ErrorInfo", "Receive file Exception!"); returnmap; } finally{releaseresource (); }                returnmap; }        /*** Release Resources *@paramSFTP *@paramsshsession *@paramChannel*/     Public voidReleaseresource () {if(Channel! =NULL) {channel.disconnect (); }        if(Sshsession! =NULL) {sshsession.disconnect (); }        if(SFTP! =NULL) {sftp.disconnect (); }    }        /*** Delete Files *@paramDirectory *@throwsException*/     Public voidDelete (String directory) {intindex = Directory.lastindexof ("/"); String dir= directory.substring (0, index); String DeleteFile= directory.substring (index + 1); System.out.println ("DIR" +dir); System.out.println ("DeleteFile" +DeleteFile); Try{sftp.cd (dir);        SFTP.RM (DeleteFile); } Catch(sftpexception e) {e.printstacktrace (); }    } }

Jsch upload (based on SFTP protocol)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.