I created a function to download files from an FTP server that I have access to. How would I upload files back to the FTP server?
Below is the download_files method i used:
public static void download_files(String un, String pw, String ip, String dir, String fn, String fp){
URLConnection con;
BufferedInputStream in = null;
FileOutputStream out = null;
try{
URL url = new URL("ftp://"+un+":"+pw+"#"+ip+"/"+dir+"/"+fn+";type=i");
con = url.openConnection();
in = new BufferedInputStream(con.getInputStream());
out = new FileOutputStream(fp+fn);
int i = 0;
byte[] bytesIn = new byte[1024];
while ((i = in.read(bytesIn)) >= 0) {
out.write(bytesIn, 0, i);
}
}catch(Exception e){
System.out.print(e);
e.printStackTrace();
System.out.println("Error while FTP'ing "+fn);
}finally{
try{
out.close();
in.close();
}catch(IOException e){
e.printStackTrace();
System.out.println("Error while closing FTP connection");
}
}
}
Use the FTPClient Class from the Apache Commons Net library.
This is a snippet with an example:
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();
}
}
Snippet taken from http://www.kodejava.org/examples/356.html
I have used the EDT FTP package, a free GPL library for FTP in Java: http://www.enterprisedt.com/products/edtftpj/overview.html
Here is a code sample, from the Demo.java class they provide:
ftp = new FTPClient();
ftp.setRemoteHost("hostname");
// connect
ftp.connect();
// login
ftp.login("user", "password");
// set up passive ASCII transfers
ftp.setConnectMode(FTPConnectMode.PASV);
ftp.setType(FTPTransferType.ASCII);
// get directory and print it to console
String[] files = ftp.dir(".", true);
for (int i = 0; i < files.length; i++)
log.debug(files[i]);
// copy file to server
ftp.put("test.txt", "test.txt");
// copy file from server
ftp.get("test.txt" + ".copy", "test.txt");
// delete file from server
ftp.delete("test.txt");
// Shut down client
ftp.quit();
Check out FTP4J as well...
Take a look at apache-commons-net they have a some FTP tools which may help you out!
Related
I am working on File Upload using Java API.
I want to upload file into server by using FTPS , I found that I can use Google library of apache commons net but I am facing issue in org.apache.commons.net.ftp.FTPSClient when i upload file.
Following is the error
Exception in thread "main" java.lang.NullPointerException
this is my code :
public static void main(String[] args) {
String server = "HOST";
int port = 21;
String user = "USER";
String pass = "PASS";
FTPSClient ftpClient;
try {
ftpClient = new FTPSClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #1: uploads first file using an InputStream
File firstLocalFile = new File("TEST1.CSV");
String firstRemoteFile = "TEST1.txt";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println("The first file is uploaded successfully.");
}
// APPROACH #2: uploads second file using an OutputStream
File secondLocalFile = new File("TEST2.CSV");
String secondRemoteFile = "TEST2.TXT";
inputStream = new FileInputStream(secondLocalFile);
System.out.println("Start uploading second file");
OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
//outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
System.out.println("The second file is uploaded successfully.");
}
} 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();
}
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any support is appreciated
I'm trying to upload image to my server but when I'm trying to open this image - it's not possible to open, apparently because it's corrupted. Can someone help me and tell me why? thanks!
I'm using the Apache Commons Net jar.
String hostName = "host";
String username = "username";
String password = "pass";
String location = "filePath.png";
FTPClient ftp = null;
InputStream in = null;
try {
ftp = new FTPClient();
ftp.connect(hostName);
ftp.login(username, password);
ftp.changeWorkingDirectory("/pictures");
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if(FTPReply.isPositiveCompletion(reply))
{
System.out.println("Connected Success");
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
File f1 = new File(location);
in = new FileInputStream(f1);
ftp.storeFile("fileName.png",in);
System.out.println("SUCCESS");
in.close();
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
My antivirus was blocking it..
I'm trying to upload an image from android to ftp server, but when i try to open the image that i uploaded i see the following message instead of the image "the image cannot be displayed because it contains errors"
and this is the code that i use
public void uploadImage(String path){
String server = "www.domainname.com";
int port = 21;
String user = "ftp-username";
String pass = "ftp-password";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #1: uploads first file using an InputStream
File firstLocalFile = new File(path);
long fileSize = firstLocalFile.length();
Log.i("File Size",fileSize+"");
String firstRemoteFile = "testfile1.jpg";
InputStream inputStream = new FileInputStream(firstLocalFile);
Log.i("uploading", "Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
if (done) {
Log.i("uploaded", "finished uploading first file");
}
// APPROACH #2: uploads second file using an OutputStream
File secondLocalFile = new File(path);
String secondRemoteFile = "testfile2.jpg";
inputStream = new FileInputStream(secondLocalFile);
Log.i("uploading", "Start uploading second file");
OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
Log.i("uploaded", "finished uploading second file");
}
} catch (IOException ex) {
Log.i("Error", "Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
where is the error!!?
Thanks in advance..
This looks suspiciously like this bug: FTPClient corrupts the images while uploading to ftp server on android?
Try using FTP4J instead.
I am working on an applet that records voice and uploads to a servlet.
Here is the code of the upload thread in the applet
class uploadThread extends Thread {
#Override
public void run() {
try {
//Preparing the file to send
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File file = File.createTempFile("uploded", ".wav");
byte audio[] = out.toByteArray();
InputStream input = new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
AudioSystem.write(ais, fileType, file);
//uploading to servlet
FileInputStream in = new FileInputStream(fileToSend);
byte[] buf = new byte[1024];
int bytesread = 0;
String toservlet = "http://localhost:8080/Servlet/upload";
URL servleturl = new URL(toservlet);
URLConnection servletconnection = servleturl.openConnection();
servletconnection.setDoInput(true);
servletconnection.setDoOutput(true);
servletconnection.setUseCaches(false);
servletconnection.setDefaultUseCaches(false);
DataOutputStream out = new DataOutputStream(servletconnection.getOutputStream());
while ((bytesread = in.read(buf)) > -1) {
out.write(buf, 0, bytesread);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error during upload");
}
}
}//End of inner class uploadThread
Here is the code of the grab file method in the servlet:
java.io.DataInputStream dis = null;
try {
int fileLength = Integer.valueOf(request.getParameter("fileLength"));
String fileName = request.getParameter("fileName");
dis = new java.io.DataInputStream(request.getInputStream());
byte[] buffer = new byte[fileLength];
dis.readFully(buffer);
dis.close();
File cibleServeur = new File("/Users/nebrass/Desktop/" + fileName);
FileOutputStream fos = new FileOutputStream(cibleServeur);
fos.write(buffer);
fos.close();
} catch (IOException ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dis.close();
} catch (Exception ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have created a certificate with the keytool. And i have signed the JAR of the applet.
I have added the applet to the jsp file and it is working, and have the all permissions (I tried to save a file on a desktop using the applet)
Update: The problem is that the file is not sent, and when i try to debug the servlet, it is not invoked by the the applet.
Please help
That's not how it works. You've just opened a URLConnection and wrote to the output stream. That way you're assuming something like a socket connection, but here we need more of a HttpUrlConnection and then a request-parameter and a multi-part request.
Google Search
Google found lots of solutions, but for the completeness of the answer, I'm adding one below :
https://stackoverflow.com/a/11826317/566092
You want up upload a file from the server to the user desktop?
I doubt this will be allowed, for obvious security reasons.
Why don't you just call the servlet directly from the browser? And "save as" the file?
Here is an exemple on how to send a file (any type) from a servlet.
protected void doPost(
...
response.setContentType("your type "); // example: image/jpeg, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/octet-stream
response.setHeader("Content-Disposition","attachment; filename=\"your_filename\"");
File uploadedFile = new File("/your_file_folde/your_file_name");
if (uploadedFile.exists()){
FileUtils.copyFile(uploadedFile, response.getOutputStream());
}
else { // Error message
}
....
}
I'm trying to upload a text file to a server via FTP. The text file is in data/data/my package/files (I have checked in the DDMS). I am getting a filenotfoundexception in LogCat.
Here's my code:
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("82.163.99.80");
client.enterLocalPassiveMode();
client.login("user", "password");
//
// Create an InputStream of the file to be uploaded
//
String filename = "sdcardstats.txt";
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();
}
}
Can anyone help please?
Your code:
fis = new FileInputStream(filename);
... requires a path, not a file name.
Try instead:
fis = openFileInput(filename);
... which takes a file name and tries to open it in your application's private file storage area. For more information, see the Android Developers Guide for Data Storage: Internal Files, and FileInputStream and openFileInput.