Using FTP and SFTP to upload pictures in Java projects __java

Source: Internet
Author: User
Tags ftp connection ftp client

In the previous article we mentioned the use of Ajax asynchronous upload pictures, here want to talk about the background of the code, because of the operating system, we want to implement the Windows environment in the project SFTP upload, Linux environment ftp upload, so make a judgment, the relevant class files are as follows:

1, first through the controller page to the picture upload page, and then through the asynchronous way to upload files, controller as follows:

@Controller public class Imageuploadcontroller {private static final Logger Logger = Logger.getlogger (imageuploadcont

    
    Roller.class);
    

    @Autowired private Imageuploadservice Imageuploadservice; @RequestMapping ("jump_image_upload.xhtml") public Modelandview Jumpuploadimage (@RequestParam (value = "Picurl"),
    Required = false) String Picurl {return new Modelandview ("Image_upload"). AddObject ("FileUrl", Picurl); @RequestMapping (value = "Image_upload.json", method = requestmethod.post) public void upload (@RequestParam (
        Value= "UploadFile") multipartfile file,httpservletrequest request,httpservletresponse response) throws IOException {
        Map<string,string> model = new hashmap<string, string> ();
        String fileName = This.generatefilename (File.getoriginalfilename ());
        String path = Request.getsession (). Getservletcontext (). Getrealpath ("Upload"); File targetfile = This.imageUploadService.getTargetFiLe (Path,filename);
            try {File.transferto (targetfile);
            This.imageUploadService.uploadImage (FileName, Targetfile.getpath ());
            Model.put ("FileUrl", Request.getcontextpath () + "/upload/" + fileName);
        Model.put ("file", fileName); catch (Exception e) {logger.error ("picture upload failed.")
            ", e); Model.put ("ErrorMsg", "picture upload failed.")
        ");
        } jsonobject JSON = Jsonobject.fromobject (model);
        Response.getwriter (). Write (json.tostring ());
    Response.getwriter (). Close (); private string Generatefilename (String fileName) {DateFormat format = new SimpleDateFormat ("yy  
        Yymmddhhmmss ");  
        String formatdate = Format.format (New Date ());  
        int random = new Random (). Nextint (10000);  
        int position = Filename.lastindexof (".");  
        String extension = filename.substring (position);  
    Return formatdate + random + extension;  }
 2, imageuploadservice as follows: 
@Service public class Imageuploadservice {         @Value ("${img.server.ip}")     PRIV


Ate String Imgserverip;


    @Value ("${img.server.port}")     private int imgserverport;


    @Value ("${img.server.username}")     private String imgserverusername;


    @Value ("${img.server.password}")     private String Imgserverpassword;
    @Value ("${img.server.ftppath}")     private String Imgserverftppath;          public void Uploadimage (String filename,string filePath) throws FileNotFoundException, Sftpexception, jschexception{        String osname = System.getproperty ("Os.name");     &NB Sp   if (Osname.startswith ("Windows"))         {            Fileutil.
Sftpuploadimg (Imgserverip, Imgserverport, Imgserverusername, Imgserverpassword, Imgserverftppath, FilePath); &nbsp      }         else         {          & nbsp Fileutil.ftpuploadimg (Imgserverip, Imgserverport, Imgserverusername, Imgserverpassword, ImgServerFtpPath, FileName,
FilePath);        }     {             /**     &NBS p;*       * function Description: Back to file object      * @param request      * @param fileName & nbsp     * @return      */    public File gettargetfile (String path,string fileName) { 
      File targetfile = new file (path, fileName);         if (!targetfile.exists ())         {          &NB Sp
Targetfile.mkdirs ();
       }         return targetfile;    }}
3, Fileutil as follows:
Both FTP and SFTP code are in this class.
public class Fileutil {   /**      * connection SFTP server      *      &NBS  p;* @param host      *             host      * @param port      *             Port      * @param username      * &N Bsp           user name      * @param password      *       &NB Sp     Password      * @return      * @throws jschexception       */&NB Sp   public static CHANNELSFTP connect (string host, int port, string Username, string password) throws Jschexception &nb Sp   {        CHANNELSFTP sftp = null;         Jsch Jsch = new Jsch ();   & nbsp
    Jsch.getsession (username, host, port);         Session sshsession = Jsch.getsession (usernAme, host, Port);
        Sshsession.setpassword (password);
        Properties Sshconfig = new properties ();
        sshconfig.put ("stricthostkeychecking", "no");
        sshsession.setconfig (sshconfig);
        sshsession.connect ();
        Channel Channel = Sshsession.openchannel ("sftp");
        channel.connect ();
        SFTP = (channelsftp) channel;
        return SFTP;    }    /**      * upload file      *       * @param Directory      *             uploaded directory      * @param uploadfile &NB Sp    *             @th files to be uploaded      * @param sftp      * Rows sftpexception      * @throws FileNotFoundException &nbsp    * @throws jschexception       */    public static void Sftpuploadimg (String ho St, int port, string userName, string password, string directory, String uploadfile) throws FileNotFoundException, Sftpexc Eption, jschexception     {        CHANNELSFTP SFTP = Connect (host, port, UserName, Passwor
D);
        SFTP.CD (directory);
        File File = new file (uploadfile);
        Sftp.put (new FileInputStream (file), File.getname ());    }    /**      * download file      *       * @param Directory      *             Download directory      * @param downloadFile &N Bsp    *             download file      * @param savefile      *             Existing local path      * @param sftp      */    public void Download (string directory, String downloadFile, Stri  Ng SaveFile, channelsftp sftp)     {        try         {   
        SFTP.CD (directory);
            File File = new file (savefile);
            Sftp.get (DownloadFile, new FileOutputStream (file));        }         catch (Exception e)         {   
        e.printstacktrace (); 
       }     {   /**      * Delete file      *       * @param directory      *             Delete file directory   &N Bsp  * @param deletefile      *             The file to be deleted      * @param sftp      */    public void Delete (string directory, String deletefile, Channelsftp sftp)     {        try         {            SF
TP.CD (directory);
            SFTP.RM (DeleteFile);        }         catch (Exception e)         {   
        e.printstacktrace ();        }     {             /**     &NBS p;*       * function Description: FTP upload      * @param host      * @param port   &nbs P   * @param userName      * @param password      * @param directory      * @param uploadfile      */    public static void Ftpuploadimg (string host, int port, string user Name, StringPassword, string directory,string orginalfilename, String uploadfile) {          FtpClient FTPCLI  ent = new FtpClient ();          FileInputStream FIS = null;          Try {              Ftpclient.connect (host);            &NBSP ; Ftpclient.login (userName, password);              File Srcfile = new File (uploadfile) ;              FIS = new FileInputStream (srcfile);          &N Bsp
 //settings upload directory               ftpclient.changeworkingdirectory (directory);              ftpclient.setbuffersize (1024);              F Tpclient.setcontrolencoding ("UTF-8");             //Set file type (binary)             &NBSP; Ftpclient.setfiletype (Ftpclient.binary_file_type);               Ftpclient.storefile (Orginalfilename, FIS);         } catch (IOException e) {              e.printstacktrace ();              throw new Runtimeexcepti On ("FTP client error. ", e);         } finally {              ioutils.closequietly ( FIS);              Try {                  Ftpclient.disconnect ();             } catch (IOException e) {      &NBS P           e.printstacktrace ();                  thro W New RuntimeException ("Shut down FTP connection) exception occurred." ", e);             }         }     }&nbsp
 }
Specifically do not explain, take your time to see it.

Related Article

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.