In my application I want to upload video using ftp. I included apache.commons.net library in my application. When I am running the code it shows 04-28 14:56:05.229: ERROR/dalvikvm(739): Could not find class 'org.apache.commons.net.ftp.FTPClient', referenced from method net.jeema.hwdvideoshare.NewVideoActivity$loadVideo.doInBackground.
How to solve this problem? I am using the below code:
protected Void doInBackground(Void... arg0) {
String hostName = "ftp.host.net";
String username = "test";
String password = "test";
String location = selectedPath;
InputStream in = null;
try {
FTPClient ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory("/uploads");
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Success");
}
File f1 = new File(location);
in = new FileInputStream(f1);
ftp.storeFile(fname, in);
System.out.println("SUCCESS");
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
When you link de lib do you have to reference it, and mark as a usable one.
maybe you forgot one of the two steps?
Open your app’s Properties dialog, navigate to “Java Build Path”->”Libraries” and add the reference.
Navigate to “Java Build Path”->”Order and Export” and select to export the two jars.
Related
Im trying to figure out how to use the mqtt broker in my android application with the AWS IoT Java SDK (https://github.com/aws/aws-iot-device-sdk-java). I know that there is an Android SDK but there are specific issues which are not part of this question. So my question is if its possible to use the Java code snippet in Android. Is there a way to have the file path of the certificate and keystore as String
String clientEndpoint = "XXXX.amazonaws.com";
String clientId ="XXX-" + System.currentTimeMillis();
String certificateFile = "/my/path/XXXX-certificate.pem.crt";
String privateKeyFile = "/my/path/XXXXX-private.pem.key";
SampleUtil.KeyStorePasswordPair pair =
SampleUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile);
AWSIotMqttClient mqttclient = new AWSIotMqttClient(clientEndpoint, clientId,
pair.keyStore, pair.keyPassword);
mqttclient.connect();
To get keystorePasswordPair the filepath is used like that in the SampleUtil class:
final List<Certificate> certChain = loadCertificatesFromFile(certificateFile);
The loadCertificateFromFile method generates a File with the filename (certificateFile) as String and obviously the file is not found because of an invalid filepath :
private static List<Certificate> loadCertificatesFromFile(final String filename) {
File file = new File(filename);
if (!file.exists()) {
System.out.println("Certificate file: " + filename + " is not found.");
return null;
}
try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file))) {
final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
return (List<Certificate>) certFactory.generateCertificates(stream);
} catch (IOException | CertificateException e) {
System.out.println("Failed to load certificate file " + filename);
}
return null;
}
Is there a way to make this work if i store the files in raw,assets or on any other place?
I have a functional web service in Jersey, that consumes a multi part form data like videos and images and stores them on a directory. I am able to upload videos and images from a browser. Now I want to upload them from an Android application by selecting from gallery Intent or camera.
How am I supposed to do so?
Any help will be appreciated. Here is my web service code.
#Path("/fileupload")
public class UploadFileService {
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
try {
String uploadedFileLocation = "/home/aamir/Downloads/" + fileDetail.getFileName();
// save it
saveToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;
return output;
}
catch(Exception e)
{
return "error";
}
}
// save uploaded file to new location
private void saveToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I suggest you use Retrofit to download the image. It's a great library for handling RESTful applications:
Use retrofit to download image file
You can use the Jersey client API in your Android app (or any other client API for that matter, Apache CXF springs to mind...). It lives in a standalone jar which you can add to your app as a dependency, then in your app create a shared client which you use to create requests.
From the Jersey client docs...
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);
https://jersey.java.net/documentation/latest/client.html
I can't access "ftp server in PC" from "android app" to download file, I used wireless connection.
public void FTP_Download(){
String server = "192.168.1.135";
int port = 21;
String user = "pc1";
String pass = "1551";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Toast.makeText(getBaseContext(), "download starting.",Toast.LENGTH_LONG).show();
// APPROACH #1: using retrieveFile(String, OutputStream)
String remoteFile1 = "i.xml";
File downloadFile1 = new File("sdcard/i.xml");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
Toast.makeText(getBaseContext(), "File #1 has been downloaded successfully.",Toast.LENGTH_LONG).show();
}
} 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();
}
}
}
I added internet permission :
<uses-permission android:name="android.permission.INTERNET"/>
Note: I tested app in emulator on PC and all things was OK.
When I tried to access FTP from default browser I can't, but I can from firefox.
any help please
I've had the same issue. If it worked on the emulator and not on the device, there's probably a firewall in your way, or your network isn't allowing the connection because for some reason it's not secure enough. Also make sure your FTP server allows connections from your username and password.
I first want to get a list of files stored in an FTP directory and then get the name of last created file using timestamp. And I'm getting an alert box: Activity is not responding. After checking logcat entry, I notice that the code never reach line :
Log.e("FTP", "number of filenames: " + count);
But I get to Log.e("FTP", "Connexion successful "); So connexion to the server seems ok.
It Seems like something going wrong out there. Can someone help me deal with it. Or show me a simple way to get the last created file from an the FTP server director?
FTPClient ftpClient = new FTPClient();
try
{
ftpClient.connect(InetAddress.getByName(Fonctions.address), Integer.parseInt(Fonctions.port));
if (ftpClient.login(Fonctions.login, Fonctions.pass))
{
Log.e("FTP", "Connexion successful ");
String workDir = ftpClient.printWorkingDirectory();
//Log.e("FTP", "workdir:" + workDir);
int count = ftpClient.listNames().length;
Log.e("FTP", "number of filenames: " + count);
FTPFile [] dossier = new FTPFile[count];
FTPFile back = new FTPFile();
dossier = ftpClient.listDirectories("Sarelo_FTP");
back = dossier[0];
Log.e("FTP", "Avant boucle " + back);
int buf = 0;
for (int i=0;i<(dossier.length) - 1;i++)
{
for (int j=1;j<dossier.length;j++)
{
buf = back.getTimestamp().compareTo(dossier[j].getTimestamp());
if (buf == -1)
back = dossier[j];
}
}
Log.e("FTP", "fichier final le plus récent: " + back.getName());
}
else{
Log.e("Restore FTP", "Error while connecting to FTP server");
}
}
catch(IOException e)
{
String title = "Error connecting to FTP server";
String msg = "Please check your parameters and connexion info: login, password,port number";
f.alert(c, title, msg).show();
Log.e("Restore FTP", "Error while connecting to FTP server", e);
}
P.S: I can't get the list of files in the directory so, I don't know if my code to retrieve the last created file is working. Any help on that would also be appreciated.
[Edit] This is my AsyncTask to retrieve the list of files in the directory. But it's still not working. I'm not getting Application Not Responding anymore, but It not seems to do anything else. Execution get stuck at the same point (can't reach Log.e("FTP", "number of filenames: " + count); )
class getFilesFromFtp extends AsyncTask
{
#Override
protected String doInBackground(Object... params)
{
int count = 0;
try
{
Log.e("FTP", "avant names: " + count);
count = ftpClient.listNames().length;
Log.e("FTP", "names: " + count);
handler.sendMessage(handler.obtainMessage());
}
catch (IOException e) {
Log.e("FTP", "Error getting number of files ", e);
}
return null;
}
}
Thanks for help.
You must not execute long running code on UI thread. Thia blocks UI redraw and event handling. It also produces ANR.
You should run it in the background thread, preferably via 'AsyncTask'.
First problem solved. I just needed to activate FTP data connection passive mode like that:
ftpClient.enterLocalPassiveMode();
before line int count = ftpClient.listNames().length;.
Hope this will help other people. Thanks to #Peter Knego driving me to AsynkTask. I learned something new. :)
I am an amateur in android coding.
I am trying to setup an android app with the ability to download a file from an ftp server. While running the code on the android 2.2 emulator, i am able to connect to the ftp server but the downloading part is showing an error. LogCat gives "download failed".
package com.ftconnect.down;
import java.io.FileOutputStream;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import org.apache.commons.net.ftp.*;
public class FTPConnectActivity extends Activity {
/** Called when the activity is first created. */
public FTPClient mFTPClient = null;
public boolean mConnect;
public boolean mDownload;
public boolean mDisconnected;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mConnect = ftpConnect("xxx.xxx.xxx.xxx", "admin",
"123456", 21);
mDownload = ftpDownload("xxx.xxx.xxx.xxx/ftp.mp3", "/sdcard");
mDisconnected = ftpDisconnect();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
Log.d("ftpConnectApp", "Connecting to " + host);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
return status;
}
} catch (Exception e) {
Log.d("ftpConnectApp", "Error: could not connect to host " + host);
}
return false;
}
public boolean ftpDownload(String srcFilePath, String desFilePath) {
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);
;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d("ftpConnectApp", "download failed");
}
return status;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
Log.d("ftpConnectApp",
"Error occurred while disconnecting from ftp server.");
}
return false;
}
}
I have setup the internet and write external permission in the android manifest file. Should i include any other permissions?
Also, let me know if there is any changes to be made to the code above. Is the destination address as '/sdcard' correct?
Thanks in advance.
You need to add Exception variable in your log message. You may also want to print full stack trace of the problem using:
e.printStackTrace();
Generally /sdcard should work, however it is more reliable to request SD card location using Environment object. See more details about file storage on android in
link
Also, let me know if there is any changes to be made to the code above. Is the destination address as '/sdcard' correct?
At the very least you should use /sdcard/filename.ext although this would only be OK for testing purposes if you are sure that /sdcard is a valid root directory.
To do things correctly, use getExternalFilesDir to find the correct path to the external storage 'files' directory that can be used for 'private' files for your own app. See the example code in that link for how to use it. You'll need to provide a filename for the output stream not just a path to a directory.
This may not be the answer to your problem but simply using...
FileOutputStream desFileStream = new FileOutputStream(desFilePath);
...when desFilePath is a directory, i.e., /sdcard, and not a file is guaranteed to fail.
Use
mFTPClient.enterLocalActiveMode();
after login