I have written a stand alone Program to upload file to FTP Server. Code runs fine but I cannot find the file at FTP. Here is the code
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPDemo {
public static void main(String[] args) {
FTPClient ftp = new FTPClient();
int reply;
try {
ftp.connect("ip address");
ftp.login("username","password");
reply = ftp.getReplyCode();
if(FTPReply.isPositiveCompletion(reply)){
System.out.println("Connected Success");
}else {
System.out.println("Connection Failed");
ftp.disconnect();
}
FileInputStream fis = null;
String filename = "demo.txt";
fis = new FileInputStream("C:\\demo.txt");
System.out.println("Is file stored: "+ftp.storeFile(filename,fis));
fis.close();
ftp.disconnect();
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Is file stored returns false. What could be the problem ?
Let me quote you the FTPClient documentation:
The convention for all the FTP command methods in FTPClient is such that they either return a boolean value or some other value. The boolean methods return true on a successful completion reply from the FTP server and false on a reply resulting in an error condition or failure. The methods returning a value other than boolean return a value containing the higher level data produced by the FTP command, or null if a reply resulted in an error condition or failure. If you want to access the exact FTP reply code causing a success or failure, you must call getReplyCode after a success or failure.
In other words, to understand the actual reason for failure you need to call ftp.getReplyCode() and work from there.
Related
I am trying to complete the last part of my Java code in Netbeans as I am fairly new. I have a client/server. I created a text file called "account.txt" and I have a username and password inside it. I'm trying to complete my code by verifying the username and password that was entered by the client is in the text file. I am including the Server code file. How do I read the username and password entered and compare them to what’s in the text file to give access to the client. I was able to write to the text file but I want to read the file to compare what the client entered is the same as what’s in the text file. I have a note in my code of where I believe the code should be.
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.stream.Stream;
public class Server {
ServerSocket serversocket;
Socket client;
int bytesRead;
Connect c = new Connect();
BufferedReader input;
PrintWriter output;
public void start() throws IOException{
System.out.println("Connection Starting on port:" + c.getPort());
//make connection to client on port specified
serversocket = new ServerSocket(c.getPort());
//accept connection from client
client = serversocket.accept();
System.out.println("Waiting for connection from client");
try {
logInfo();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
public void logInfo() throws Exception{
//open buffered reader for reading data from client
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
String username = input.readLine();
System.out.println("SERVER SIDE" + username);
String password = input.readLine();
System.out.println("SERVER SIDE" + password);
// *************update this add read text file********************
File file = new File("accounts.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
if(username.equals(c.getUsername()) &&password.equals(c.getPassword())){
output.println("Welcome, " + username);
}else{
output.println("Login Failed");
}
output.flush();
output.close();
}
public static void main(String[] args){
Server server = new Server();
try {
server.start();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Well, I finally answered my own question on here. How I got it to work was by creating three files, client, server, and log in. I called the login method from the client, so when the client authenticates the login calls the server to proceed with the file request. if the file exists, it will send it through the port but if it doesn't it will let the client know the file does not exist. Let me know if you want to see my finished code.
Hello Every one i am working one project where i need to upload file on my ftp server with my java standalone application
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class Ftpdemo {
public static void main(String args[]) {
// get an ftpClient object
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(300);
FileInputStream inputStream = null;
try {
// pass directory path on server to connect
ftpClient.connect("ftp.mydomain.in");
// pass username and password, returned true if authentication is
// successful
boolean login = ftpClient.login("myusername", "mypassword");
if (login) {
System.out.println("Connection established...");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
inputStream = new FileInputStream("/home/simmant/Desktop/mypic.png");
boolean uploaded = ftpClient.storeFile("user_screens/test3.png",inputStream);
if (uploaded) {
System.out.println("File uploaded successfully !");
} else {
System.out.println("Error in uploading file !");
}
// logout the user, returned true if logout successfully
boolean logout = ftpClient.logout();
if (logout) {
System.out.println("Connection close...");
}
} else {
System.out.println("Connection fail...");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
its working fine for the data which is 1 or 2 kb but when i try to upload the file which is of 50 kb and 100 kb then it not working fine. The image uploaded on the server is blank .
As far as I can see, there is nothing wrong with the code. As you're saying 1 or 2 kb of data uploading works fine. So, In my opinion, there is problem with your internet. Might be it's too slow to upload a file size of 50 kb or more.
There is noting wrong with your code only issue with the file or internet speed.Code is working fine here and Also there is recommended that NOT TO USE FTP DETAILS DIRECTLY please avoid this stuff from application you have better option to use web service for your server related stuff.
Good Luck
It seems you had not made connection Instances properly.
Please refer my working code:
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader() throws Exception {
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(new FileOutputStream("c:\\ftp.log"))));
int reply;
ftp.connect(Constant.FTP_HOST);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception(Constant.FTP_SERVER_EXCEPTION);
}
ftp.login(CommonConstant.FTP_USERNAME, Constant.FTP_PASSWORD);
ftp.setFileType(FTP.TELNET_TEXT_FORMAT);
ftp.enterLocalPassiveMode();
}
public boolean uploadFile(File localFileFullName, String fileName) throws Exception {
InputStream input = new FileInputStream(localFileFullName);
boolean reply = this.ftp.storeFile("'" + fileName +"'", input);
disconnect();
return reply;
}
public void disconnect() {
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException e) {
System.out.println(this.getClass()+ e);
}
}
}
public static void main(String[] args) throws Exception {
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader();
System.out.println(ftpUploader.uploadFile(new File("C:\\test.txt"), "Destinate_DIR"));
System.out.println("Done");
}
}
All the best ...!!!
I would like to use org.apache.commons.net.ftp.FTPClient in my JSF application. How client side (Web Browser) upload to my web application server for large file. Even if I use RichFaces File Upload or PrimeFaces File Upload, client browser can use HTTP Protocol. How can I support FTP Protocol to client browser? Could you provide the better way?
Cause : the application user cannot direct access to our Repository Server(SVN). Firstly, they have to upload the files to our application on Web AS. And then, the application checkin/chekout to RepositoryServer. The application user can upload the file which has 500M to 2G at least. That's why, I am thinking, how can I support FTP Protocol to browser client' to be faster. Otherwise, am I thinking wrong?
In order to be able to send a file to a FTP server, you obviously need a FTP client.
However, a webbrowser is a HTTP client, not a FTP client. This is a natural functional design limitation of the webbrowser. JSF look like a magician, but here it really can't do anything for you. It intercepts on HTTP requests/responses only.
Indeed, you're thinking wrong. Just stick to uploading the file the usual HTTP way. If you're absolutely positive that you need FTP for this for some reason, then your best bet is most likely homebrewing a Java Applet for this, but this would after all be plain clumsy.
First do HTTP upload through primefaces to a temporary directory. then through org.apache.commons.net.ftp.FTPClient or through sun.net.ftp.FtpClient upload to the required FTP Server.
Below is an example;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import sun.net.ftp.FtpClient;
/**
*
* #author fali
*/
public class FtpUtil {
public String server, username,password, remote, remotedir, local;
FtpClient ftp;
public static int BUFFER_SIZE = 10240;
public FtpUtil(){
server = "localhost";
username = "anonymous";
password = " ";
remotedir = "/incoming";
remote = "dvs.txt";
local = "C:\\dvs.txt";
}
protected void putFile() {
if (local.length() == 0) {
System.out.println("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(local);
int size = (int) f.length();
System.out.println("File " + local + ": " + size + " bytes");
System.out.println(size);
FileInputStream in = new FileInputStream(local);
OutputStream out = ftp.put(remote);
int counter = 0;
while (true) {
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
System.out.println(counter);
}
out.close();
in.close();
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
public String Upload(){
String result="";
try{
ftp = new FtpClient(server);
ftp.login(username, password);
System.out.println(ftp.welcomeMsg);
ftp.cd(remotedir);
putFile();
disconnect();
}catch(Exception ex){
System.out.println(ex);
result = "Error : "+ex;
}
return "";
}
protected void disconnect() {
if (ftp != null) {
try {
ftp.closeServer();
} catch (IOException ex) {
}
ftp = null;
}
}
}
In your managedbean/controller;
public String create() {
System.out.println("Request Button Clicked");
try {
// generate reference number
//current.setReferenceno(genReferenceNo());
// add to database
//getFacade().persist(current);
// upload to ftp
FtpUtil fu = new FtpUtil();
fu.Upload();
// show reference number
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("QueueCreated"));
JsfUtil.addSuccessMessage("Your Reference No. is :" + current.referenceno);
current = null;
// try {
// System.out.println("Redirecting");
// FacesContext.getCurrentInstance().getExternalContext().dispatch("/");
// } catch (Exception ex) {
// System.out.println(ex);
// }
return "";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
and some thing like this in your page;
<br />
<ppctu:commandButton action="#{appointmentController.create}" type="Submit" value="Request" />
I am trying to store a byteArrayInputStream as File on a FTP Server. I could already connect to the Server and change the working path, but triggering the method to store the Stream as File on the Server returns always false.
I am using the apache FTPClient.
Can someone please give me a hint where my mistake can be!?
Here the Code:
String filename = "xyz.xml"
// connection returns true
connectToFtpServer(ftpHost, ftpUser, ftpPassword, exportDirectory);
// byteArray is not void
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
try {
// change returns true
result = ftpClient.changeWorkingDirectory(exportDirectory);
// storing the file returns false
result = ftpClient.storeFile(filename, byteArrayInputStream);
byteArrayInputStream.close();
ftpClient.logout();
} catch (...) {
...
} finally {
// disconnect returns true
disconnectFromFtpServer();
}
I don't believe it's your code. Here is another example that looks very similar from kodejava:
package org.kodejava.example.commons.net;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FileUploadDemo {
public static void main(String[] args) {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// Create an InputStream of the file to be uploaded
//
String filename = "Touch.dat";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I agree it's file permissions. There is not a way to change permissions in java itself yet, but there are other solutions. See this thread: How do i programmatically change file permissions?
HTH,
James
It was actually a permission issue due to an invalid usergroup. After adding my user to the usergroup, i was able to store again files.
I have the following method to upload_files to an FTP server, I am not receiving any errors yet the file is not appearing on the server after its run. What could be the problem?
public static void upload_files(String un, String pw, String ip, String dir, String fn){
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(ip);
client.login(un, pw);
String filename = dir+"/"+fn;
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
System.out.println("uploaded");
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are a number of possible issues. Assumption is that you are using FTPClient 3.x from Apache commons-net. If using something else, you should probably indicate that in your question. Ideas:
Check the reply status of the connection to make sure you are connecting as expected. There's an example on how to do this in the JavaDoc.
Your filename variable is the path to the local file you want to send. Is that really the same path you want to use for storing the file on the server (relative to the FTP login root)? It might be, but usually isn't. If not, your first parameter to client.storeFile(...) needs to be changed.
Most FTP servers provide ability to log all actions. Are you able to access yours? If so, that usually quickly makes clear what is going wrong.