Java ftp download file and Coding issues Summary

Source: Internet
Author: User

Problem

Before in the development process, encountered a bit of a problem, I want to access an FTP server to download the file details as follows:

1. Need to pass in a file name that may be in Chinese;

2. Search for the file by file name on FTP;

3. The FTP server name code is "GBK";

Ideas

1. The file name is directly behind the URL via the Get method, but it needs to be transcoded;

2. After receiving parameters in Java controller, decode and decode to normal data;

3. With normal data re-transcoding to GBK, to the service to call FTP can

4. (For corporate security reasons, we need to call FTP in another module) the file name is passed through the rest interface, another module gets the file stream converted to byte[], and the response output is called

Solutions to summarize coding problems:

jquery for URL and parameter transcoding, as far as I know the main application encodeURI, encodeURIComponent, for example I need to pass in a variable named filedepence

var downloaddepence=fileid+"-"+filename;window.location.href=encodeURI( ajaxurl+"/coadownload/downloadfile?filedepence="+encodeuricomponent(downloaddepence));

This way I can receive the filedepence after transcoding in the background, by verifying that encodeURIComponent will transcode with "Utf-8", so we use Java to decode it:

String Viewitem=java.net.urldecoder.decode (filedepence, "utf-8");

The resulting viewitem is the same as the value we originally want to pass in, if the Chinese file name is passed in, then ViewItem is the corresponding Chinese file name.

After I understand again, through JS to complete the GBK transcoding more trouble, and the use of Unicode Java comparison method, then the same, we use ViewItem in GBK to the code, you can get the corresponding FTP server file name.

String gbkitem= Urlencoder.encode (ViewItem, "GBK");
Workaround for FTP

Create a common class of FTP connections

 Public StaticFtpClient connectftp (String URL,intport, string Username, string password) {        //Create FTPFtpClient FTP =NULL; Try {            //Create an addressSocketAddress addr =Newinetsocketaddress (URL, port); //ConnectionFTP =ftpclient.create ();            Ftp.connect (addr); //LoginFtp.login (username, Password.tochararray ());        Ftp.setbinarytype (); } Catch(ftpprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } logger.info ("Logged in to FTP server!" +NewDate ()); returnftp; }

A downloaded method is established in the service of another module, which is called in the controller that is accessed by the rest interface.

  PublicFilebtye downloadfilefromftp (String filedepence,httpservletresponse response)throwsIOException, ftpprotocolexception {Filebtye file=NewFilebtye (); //filebtye is an object that contains only btye[], and is primarily used for JSON outgoing response.setcharacterencoding for responsebody that is appropriate for a controller ("Utf-8"); Filedepence=filedepence.replace ("\" "," "));        //rest Interface transmitted values need to be processed in a certain format FtpClient ftpclient=ftpmanager.connectftp (Ftphost, Integer.parseint (FtpPort), FtpUserName, FTPPassword);        //Read through properties file InputStream is=NULL; Ftpclient.changedirectory ("//filepath"); //File directory  is=Ftpclient.getfilestream (filedepence);        //Get file stream Bytearrayoutputstream Swapstream=NewBytearrayoutputstream (); byte[] Buff =New byte[100];//buff for storing temporary data that is read in a loop        intrc = 0;  while(rc = is.read (buff, 0,)) > 0) {swapstream.write (buff,0, RC); }        byte[] Filebyte =Swapstream.tobytearray ();        File.setfileinfo (Filebyte);        Is.close (); returnfile; }

Call the rest interface in the local service to complete the output response output, while paying attention to the response settings

String Viewitem=java.net.urldecoder.decode (filedepence, "Utf-8"); //FTP Server Naming conventions with GBK encodingString gbkitem= Urlencoder.encode (ViewItem, "GBK");
       //Call the rest interface to get the returned Filebtye Filebtye Downloadstream
=resttemplate.postforobject (Gatewayrooturl + gatewayurlconstant.coa_download + gatewayurlconstant.download_file, Gbkitem, Filebtye.class); if(downloadstream!=NULL){ //Set Information HeaderResponse.setcharacterencoding ("Utf-8"); //Set the encoding Response.setcontenttype ("Multipart/form-data"); //According to the file to determine the file format response.setheader ("Content-disposition", "attachment;filename=" +ViewItem); //Set file name Servletoutputstream out; //Output Stream outputout =Response.getoutputstream (); Out.write (Downloadstream.getfileinfo ()); Out.flush (); Out.close (); Logger.info ("Download file succeeded" +NewDate ()); }Else{logger.info ("Download file does not exist" +NewDate ()); }

Java ftp download file and Coding issues summary

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.