Below is the code sample which can be directly used to upload a file via FTP using Java
Following are the features
- Using properties file to configure the FTP details
- Ready to use code for browsing a file & upload to FTP
- Tested in both windows & Linux environments
- Provision to restrict the type of file & size of file to be uploaded
uploadfile.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>::FILE UPLOAD TO FTP USING JAVA::</title>
</head>
<body>
<form action="postUpload.jsp" method="post" enctype="multipart/form-data" name="form1">
<table width="200" border="1">
<tr>
<td nowrap="nowrap">File Upload: </td>
<td><input type="file" name="file1" id="file1" /></td>
</tr>
<tr>
<td><input type="submit" value="Upload" name="Submit" /></td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
resource_properties.java
import java.util.MissingResourceException;
import java.util.Locale;
import java.util.ResourceBundle;
public class FtpResource_Properties
{
/**
* The main method.
*
* @param ar
* the arguments
*/
public static void main(String ar[])
{
Locale currentLocale = new Locale("EN","IN");
}
public ResourceBundle getproperties_Ftp()
{
Locale currentLocale = new Locale("EN","IN");
ResourceBundle myFtpResource = ResourceBundle.getBundle("com.tpa_ftp_IN",currentLocale);
return myFtpResource;
}
}
tpa_ftp_IN.properties
ftp_host = YOUR FTP HOST
ftp_username= YOUR FTP USERNAME
ftp_pwd= YOUR FTP PASSWORD
ftp_port= YOUR FTP PORT
ftp_portread=YOUR FTP PORT TO RETRIEVE FILES
postUpload.jsp
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.ResourceBundle" %>
<%@ page import="sun.net.ftp.FtpClient" %>
<%@ page import="org.apache.commons.net.ftp.*" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.net.URL" %>
<%@ page import="com.FtpResource_Properties.*" %>
<%
boolean filesaved=false;
String filename=null;
String targetfilename=null;
int maxuploadsize=0;
boolean isMultipart = FileUpload.isMultipartContent(request);
DiskFileUpload upload = new DiskFileUpload();
// parse this request by the handler
// The code below will provide a list of items from the request
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
try
{
FileItem item = (FileItem) itr.next();
File SourceFile = new File(item.getName());
item.write(SourceFile);
long size =SourceFile.length();
maxuploadsize=size/1024;
filename=SourceFile.getName();
filename=filename.substring(fname.lastIndexOf("."));
String extension=(filename.substring(1)).toLowerCase();
targetfilename="filename";
System.out.println(extension);
//Validating the file upload size
if( maxuploadsize<=2000)
{
System.out.println("correct size");
//Validating the file types which can be uploaded
if(("jpg".equals(extension) || "doc".equals(extension) ||"pdf".equals(extension) ||"tif".equals(extension) || "xls".equals(extension) || "docx".equals(extension)|| "xlsx".equals(extension) || "tiff".equals(extension) ) )
{
System.out.println("correct Extension");
}
}
else
{
SourceFile.delete();
}
filename=targetfilename+"."+extension;
}
catch(Exception e)
{
System.err.println(E.getMessage());
E.printStackTrace();
}
finally
{
SourceFile.delete();
}
try
{
//FTP conenction code
ResourceBundle myFtpResource = new FtpResource_Properties().getproperties_Ftp();
//Retrieve FTP Host from properties file
String ftphost=myFtpResource.getString("ftp_host");
//Retrieve FTP USername from properties file
String ftpuser=myFtpResource.getString("ftp_username");
//Retrieve FTP Password from properties file
String ftppassword=myFtpResource.getString("ftp_pwd");
//Retrieve FTP Port from properties file
int ftpport=Integer.parseInt(myFtpResource.getString("ftp_port"));
// Retrieve FTP port for retrieving the file from properties file
int ftpportread=Integer.parseInt(myFtpResource.getString("ftp_portread"));
FTPClient ftp = new FTPClient();
ftp.connect(ftphost,ftpport);
ftp.login(ftpuser,ftppassword);
System.out.println("successfully connected");
//Below code will be used to check whether the target folder exists in FTP in the specified path. If not exists, will create the specific target folder
URL u = new URL("http://"+ftphost+":"+ftpportread+"/targetfoldername/");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
int rc = huc.getResponseCode();
//If target folder does not exists
if(rc==404)
{
String path="/targetfoldername";
ftp.makeDirectory(path);
}
//Converting the source file to FileInput Stream
FileInputStream fis=new FileInputStream(SourceFile);
String targetpfolderpath="/targetfoldername/";
ftptest ft=new ftptest(ftphost, ftpuser, ftppassword,ftpport,fis,targetpfolderpath+filename+"" );
filesaved=true;
//Disconnecting the FTP
ftp.disconnect();
}
catch(Exception e)
{
System.err.println(E.getMessage());
E.printStackTrace();
}
finally
{
SourceFile.delete();
}
%>
ftptest.java
import java.io.*;
import java.net.*;
public class ftptest
{
protected FtpClient con;
public final FileInputStream sourcefile;
public final String targetfile;
public ftptest(String _host, String _user, String _password,int _port,FileInputStream _sourcefile, String _targetfile)
{
con = new FtpClient(_host, _user, _password,_port);
sourcefile = _sourcefile;
targetfile = _targetfile;
upload();
}
protected void upload()
{
try
{
OutputStream os = con.openUploadStream(targetfile);
FileInputStream is = sourcefile;
byte[] buf = new byte[100000];
int b;
while (true)
{
b = is.read(buf);
if (b <= 0) break;
os.write(buf, 0, b);
System.out.print("Uploading File to FTP");
}
os.close();
os.flush();
is.close();
con.close();
}
catch (Exception E)
{
System.err.println(E.getMessage());
E.printStackTrace();
}
}
public static void main(String args[])
{
//
}
}
class FtpClient
{
public final String host;
public final String user;
protected final String password;
protected final int port;
protected URLConnection urlc;
public FtpClient (String _host, String _user, String _password,int _port)
{
host = _host;
user = _user;
password = _password;
port=_port;
urlb = null;
}
protected URL genURL(String targetfile) throws MalformedURLException
{
if (user == null)
return new URL("ftp://"+ host+ "/"+ targetfile+ ";type=i");
else
return new URL("ftp://"+ user+ ":"+ password+ "@"+ host+ "/"+ targetfile+ ";type=i");
}
protected InputStream openDownloadStream(String targetfile) throws Exception
{
URL url = genURL(targetfile);
urlb = url.openConnection();
InputStream is = urlb.getInputStream();
return is;
}
protected OutputStream openUploadStream(String targetfile) throws Exception
{
URL url = genURL(targetfile);
urlb = url.openConnection();
OutputStream os = urlb.getOutputStream();
return os;
}
protected void close()
{
urlb = null;
System.gc();
}
}
No comments:
Post a Comment