I use the following piece of code to upload a photo to a ftp host. But the photo seems to be corrupted after being uploaded:
There are narrow gray lines at the bottom of the photo.
The size of gray lines could be decreased by decreasing the Buffer Size of the FTPClient object.
import java.io.File;
import java.io.FileInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import sun.misc.Cleaner;
public class FtpConnectDemo1 {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("ftp.ftpsite.com");
//
// When login success the login method returns true.
//
boolean login = client.login("user#ftpsite.com", "pass");
if (login) {
System.out.println("Login success...");
int replay = client.getReplyCode();
if (FTPReply.isPositiveCompletion(replay)) {
File file = new File("C:\\Users\\e.behravesh\\Pictures\\me2_rect.jpg");
FileInputStream input = new FileInputStream(file);
client.setFileType(FTP.BINARY_FILE_TYPE);
if (!client.storeFile(file.getName(), input)) {
System.out.println("upload failed!");
}
input.close();
}
//
// When logout success the logout method returns true.
//
boolean logout = client.logout();
if (logout) {
System.out.println("Logout from FTP server...");
}
} else {
System.out.println("Login fail...");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//
// Closes the connection to the FTP server
//
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
this is known error resolved in newest version of library:
http://commons.apache.org/net/changes-report.html#a3.0.1
Never ever heard of corruption of that type, but: are you uploading from behind a firewall? Try doing client.enterLocalPassiveMode(); before calling storeFile.
I've just tried your code on my local computer and it works. I didn't see any gray lines.
So I guess this is either a passive mode thing as Femi suggest or some network/firewall/lower-level problem.
probably late, but it could help somone to avoid waste time.
Check conf file and permitions!! In Unix using vsftp check that
write_enable=YES
stay uncomment.
Check with another FTP client if it posible to upload files.
FTP file sending is not atomic meaning that if there was a crash in the connection only partial file has been send. i would offer add change name to know when transfer is completed in the end of file send.
Related
This bug is happening only in win10. Currently in win7 it does not happen.
Essentially I write some text that the user has inputted in various fields.
I use this to save all the info the user wrote, so when the application is relaunched the info is already there.
Also, I call this class every time the user clicks a button.
With normal behavior, the application runs fine on win7, and it saves everything properly. With win10 though, saving effectively "corrupts" the file, or at least, it makes it empty.
package whatever;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class SaveFile {
public static void mainSave(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
String instaPathCombined = "config.properties";
output = new FileOutputStream(instaPathCombined);
// set the properties value, the get methods all retrieve a string.
prop.setProperty("a", UI.geta());
prop.setProperty("b", UI.getb());
prop.setProperty("c", UI.getc());
prop.setProperty("d", UI.getd());
prop.setProperty("e", UI.gete());
prop.setProperty("f", UI.getf());
prop.setProperty("g", UI.getg());
prop.setProperty("h", UI.geth());
prop.setProperty("i", UI.geti());
prop.setProperty("j", UI.getj());
prop.setProperty("k", UI.getk());
prop.setProperty("l", UI.getl());
prop.setProperty("m", UI.getm());
prop.setProperty("n", UI.getn());
prop.setProperty("o", UI.geto());
prop.setProperty("p", UI.getp());
prop.setProperty("q", UI.getq());
prop.setProperty("r", UI.getr());
prop.setProperty("s", UI.gets());
prop.setProperty("t", UI.gett());
prop.setProperty("u", UI.getu());
prop.setProperty("v", UI.getv());
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I have no idea on why it does this.
Also, this is literally a win10 issue, no other factors matter here, as I tried it on a VM with a fresh win10 installation and it happened.
I am creating a Java HTTP server that checks to make sure a client is not banned before redirecting to the main server. I have already created everything for the server that is needed, I just don't know how to redirect to another port that is running the main server. Here is my code:
package netlyaccesscontrol;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class AllowedCheck {
public static void main(String[] args) {
String line = null;
try {
FileReader reader = new FileReader("Banned.txt");
BufferedReader buffer = new BufferedReader(reader);
ServerSocket s = new ServerSocket(80);
Socket c = s.accept();
String clientIP = c.getInetAddress().toString();
while ((line = buffer.readLine()) != null) {
if (clientIP == line) {
s.close();
} else {
// redirect to main server here
}
}
} catch (FileNotFoundException ex) {
System.out.println("The banned IP address file does not exist.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The redirection that you are thinking of is something supported by HTTP and the browsers. There's a specific HTTP response code that tells the caller to redirect and a way to specify it.
Raw sockets are a low-level network protocol that is not going to support redirection as you expect. The most you might be able to do is have this program be a proxy and, upon success, push all incoming data/outgoing responses to/from the ultimate server. But what you have here is by no means going to cut it.
I'm trying to use the printWorkingDirectory() from Apache Commons FTP but it's only returning null. I can't navigate directories, list files, etc.
Log in pass all is success but how ever I try I can not change current directory.
I use this following code:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FTPDownloadFileDemo {
public static void main(String[] args) {
String server = "FTP server Address";
int port = portNo;
String user = "User Name";
String pass = "Pasword";
FTPClient ftpClient = new FTPClient();
String dir = "stocks/";
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
System.out.println( ftpClient.printWorkingDirectory());//Always null
//change current directory
ftpClient.changeWorkingDirectory(dir);
boolean success = ftpClient.changeWorkingDirectory(dir);
// showServerReply(ftpClient);
if (success)// never success
System.out.println("Successfully changed working directory.");
System.out.println(ftpClient.printWorkingDirectory());// Always null
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This is rather old question that deserves an answer. This issue is likely a result of using FTPClient when secure connection is required. You may have to switch to FTPSClient if that is, indeed, the case. Further, output the response from the server with the following code snippet to troubleshoot the issue if secure client doesn't solve the it:
ftpClient.addProtocolCommandListener(
new PrintCommandListener(
new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")), true));
Also, a server can reject your login attempt if your IP address is not white listed. So, being able to see the logs is imperative. The reason you see null when printing current working directory is because you are not logged in. Login method will not throw an exception but rather return a boolean value indicating if the operation succeeded. You are checking for success when changing a directory but not doing so when logging in.
boolean success = ftpClient.login(user, pass);
I faced the same, but I came across with a simple step.
Just added this.
boolean success = ftpClient.changeWorkingDirectory(dir);
ftpClient.printWorkingDirectory(); //add this line after changing the working directory
System.out.println(ftpClient.printWorkingDirectory()); //wont be getting null
Here I have the code and the console output
FTPClient.changeWorkingDirectory - Unknown parser type: "/Path" is current directory
I know I replied too soon ;-P, but I saw this post recently. Hope this helps to future searchers ;-)
I am trying to download a file from a server. The server has a guest account without a login or password.
The code was adapted from http://www.dreamincode.net/forums/topic/32031-ftp-in-java-using-apache-commons-net. The reply code is 220, which means "Service ready for new user", but the size of the downloaded file is 0 Bytes. The size of the file on the server is 845 Bytes.
Thank you for your time.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpTest {
public static FTPClient ftp = new FTPClient();
public static void main(String []args) throws IOException{
String ftpStr = "ftp.ncbi.nih.gov";
String path = "ftp.ncbi.nih.gov/genomes/MapView/Mus_musculus/non_sequence/README";
try {
ftp.connect(ftpStr);
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
int reply = ftp.getReplyCode();
System.out.println(reply); //Output: 220
System.out.println("Connected");
File file = new File("README");
FileOutputStream dfile = new FileOutputStream(file);
ftp.retrieveFile(path,dfile);
ftp.disconnect();
System.out.println("Finished");
}
}
To access an FTP server with a guest account (without username or password), you should use the username anonymous with an empty password.
I know this is two years late, but I had the same issue. The variable remote in: public boolean retrieveFile(String remote, OutputStream local) throws IOException
expects a file name, not the the full address to the file. So you should pass "README" instead of path. Before doing that, you should change the working directory of your ftp client to "genomes/MapView/Mus_musculus/non_sequence"
I'm trying to use my phone as a realtime MJPEG video source. So far, capturing frames and converting them into JPEGs is no big deal. My real issue is sending the multipart response properly. There's tons of documentation about sending multipart responses out there, but the issue with them is that they all expect that all of the images are available at the time the HTTP request comes in (such as would be used for a multi-image upload). In order to stream in realtime, of course, I need to be able to begin to send the multipart response while continually adding jpegs in the body. I'm by no means a HTTP buff, so it's not desirable for me be required to roll my own HTTP response and write directly to a socket. Is there a library out there that supports this kind of behavior? I've scoured the internet for solutions, but I really don't see anything useful out there.
Any ideas? Worst case scenario, I'd be willing to look at human-readable documentation of how to write a multipart response by hand, but I'd really just rather use a library if that's possible.
Thanks in advance.
edit: got it working using the orielly servlet library as per sigmavirus' suggestion. Note that the MJPEG stream is more or less implicitly inferred from the fact that I'm sending a multipart/x-mixed-replace that only has image/jpeg's in it. Check out the comment in my code for a tutorial that shows what jetty libraries you'll need to get this running. Of course, you'll additionally need cos.jar, the Orielly servlet library. The code follows:
package edu.stevens.arpac.webclient;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.conn.util.InetAddressUtils;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.Request;
import com.oreilly.servlet.MultipartResponse;
import com.oreilly.servlet.ServletUtils;
import android.os.Environment;
import android.util.Log;
// holla at http://puregeekjoy.blogspot.com/2011/06/running-embedded-jetty-in-android-app.html
public class JettyServer extends Thread
{
private static final String TAG = "JettyServer";
private Server webServer;
private Boolean isStarted = false;
public JettyServer()
{
super();
Log.i(TAG, "Initializing server to port 8080");
webServer = new Server(8080);
Handler handler = new AbstractHandler() {
public void handle(String target, Request request, HttpServletRequest servletRequest,
HttpServletResponse servletResponse) throws IOException, ServletException {
ServletOutputStream out = servletResponse.getOutputStream();
MultipartResponse multi = new MultipartResponse(servletResponse);
Boolean go = true;
while( go )
{
try
{
multi.startResponse("image/jpeg");
ServletUtils.returnFile(Environment.getExternalStorageDirectory().getPath() + "/ARPac/twi.jpg", out);
multi.endResponse();
}
catch(IOException ex)
{
go = false;
Log.i(TAG, "IO Failed with exception " + ex.getMessage());
}
}
request.setHandled(true);
}
};
webServer.setHandler(handler);
try {
webServer.start();
Log.d(TAG, "started Web server # " + getIPAddress());
isStarted = true;
}
catch (Exception e) {
Log.d(TAG, "unexpected exception starting Web server: " + e);
}
}
/**
* Get IP address from first non-localhost interface
* #return address or empty string
*/
private String getIPAddress()
{
try
{
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces)
{
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs)
{
if (!addr.isLoopbackAddress())
{
String sAddr = addr.getHostAddress().toUpperCase();
if (InetAddressUtils.isIPv4Address(sAddr))
{
//Log.d(TAG, "IP address is: " + sAddr);
return sAddr;
}
}
}
}
}
catch (Exception ex)
{
Log.e(TAG, "could not get IP address: " + ex.getMessage());
} // for now eat exceptions
Log.e(TAG, "Could not find a non-loopback IPv4 address!");
return "";
}
public void teardown()
{
if( isStarted )
{
try {
webServer.stop();
isStarted = false;
} catch (Exception e) {
Log.e(TAG, "Couldn't stop server. Probably was called when server already stopped.");
}
}
}
public void run()
{
}
}
Have you seen this? http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartResponse.html It looks like the example sends each part individually and waits a specified time limit before sending the next or receiving an interrupt.