File is not uploading on Ftp server in java? - java

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 ...!!!

Related

Java download textfile from FTP empty textfile

Hi I'm trying to get my program to download a text document from my FTP server.
This is the code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
public class NetTestFTP {
public static void main(String[] args) {
FTPClient client = new FTPClient();
OutputStream outStream;
try {
client.connect("82.44.221.198");
client.login("User", "Pass");
String remoteFile = "/hello.txt";
outStream = new FileOutputStream("hello.txt");
client.retrieveFile(remoteFile, outStream);
} catch (IOException ioe) {
System.out.println("Error communicating with FTP server.");
} finally {
try {
client.disconnect();
} catch (IOException e) {
System.out.println("Problem disconnecting from FTP server");
}
}
}
}

Java FTP 550 error

I'm getting this error (550 the filename, directory name, or volume label syntax is incorrect. )
I think the url is correct (obviously not though). Any thoughts?
Here is the url:
STOR /images/report/6F81CB22-3D04-4BA3-AC3F-3D34663449E0**9.png
Here is the invocation method:
private void uploadImageToFtp(String location, String imageName) throws Exception{
File imageFile = new File(location);
System.out.println("Start");
FTPUploader ftpUploader = new FTPUploader("ftp.xxx.com", "user", "password");
ftpUploader.uploadFile(imageFile, imageName, "/images/report/");
imageFile.delete();
ftpUploader.disconnect();
System.out.println("Done");
}
Here is the
ftp class:
package server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUploader {
FTPClient ftp = null;
public FTPUploader(String host, String user, String pwd) throws Exception{
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void uploadFile(File file, String fileName, String hostDir)
throws Exception {
try {
InputStream input = new FileInputStream(file);
this.ftp.storeFile(hostDir + fileName, input);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void disconnect(){
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException f) {
// do nothing as file is already saved to server
f.printStackTrace();
}
}
}
}
If the FTP server is running Windows, the '*' characters are the problem. Windows file names may not have asterisks.
Try changing working directory first before uploading
ftp.changeWorkingDirectory(DESTPATH);
It worked for me.

video streaming from Android without saving on sdcard

I have code:
private MediaRecorder recorder;
String hostname = "192.168.1.125";
int port = 1935;
Socket socket;
ParcelFileDescriptor pfd;
public void start()
{
try {
socket = new Socket(InetAddress.getByName(hostname), port);
pfd = ParcelFileDescriptor.fromSocket(socket);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.setOutputFile(pfd.getFileDescriptor());
// String filename = String.format("/sdcard/%d.mp4", System.currentTimeMillis());
//
// recorder.setOutputFile(filename);
try
{
recorder.prepare();
recorder.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
And Server side:
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args)
{
try
{
System.out.println("create sock");
ServerSocket svsock = new ServerSocket(1935);
System.out.println("accept");
Socket sock = svsock.accept();
System.out.println("buffer read");
FileOutputStream outFile = null;
String filename = String.format("%d.mp4", System.currentTimeMillis());
try {
outFile = new FileOutputStream(filename);
System.out.println(filename);
} catch (IOException e1) {
e1.printStackTrace();
}
InputStream is = new DataInputStream(sock.getInputStream());
byte[] byteBuffer = new byte[1024];
int allsize = 0;
while(sock.isConnected()) {
int size = is.read(byteBuffer);
if (size == -1){
break;
} else {
outFile.write(byteBuffer, 0, size);
}
allsize += size;
}
System.out.println("close size=" + allsize);
outFile.close();
sock.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("endmain");
}
}
I test it on Android 2.2.2 (HTC quiet brilliant) and all works fine. When I press "start" button Server create file and record data from stream to file. After this file is normally play in VLC player and etc.
But when I test it on Android 4.0.4 (Galaxy S2) Server create file and record data from stream to file but not play in VLC (and other players too) and give me error
mp4 error: MP4 plugin discarded (no moov,foov,moof box)
avcodec error: Could not open �codec demux error: Specified event object handle is invalid
ps error: cannot peek
main error: no suitable demux module for `file/:///C:/1345461283455.mp4'
I also try to upload this file to youtube, but after upload youtube give me error like file format is unsupported.
But Android 4.0.4 (Galaxy S2) succesfully create and then play file when I save it on phone memory (not stream to server)
I think problem maybe on server side, or something changed on android 4.0.4.
Please, help me.
Thanks in advance.
try this
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setOutputFile(pfd.getFileDescriptor());
I think it should solve the problem. Give it a try and see if it helps ...

File not uploading successfully to FTP

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.

Java - Storing File on FTP Server fails

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.

Categories

Resources