Error in uploaing file from android to ftp server - java

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.

Related

Download all the files from Azure blob storage , zip it and upload the zip file in JAVA

I want to download all the files from Azure blob storage, create a zip file out of these files and upload the zip file back to the blob storage.
As the file size can be very large, I dont want to max out the memory.
Also this operation needs to be very FAST.
JAVA SDK - azure-storage-blob 12.8.0
EDIT : Code written so far. Not sure how to proceed further with uploading pipedinputstream data parallely.
String zipFileName = formFileName(exportRequest, requestId);
final PipedOutputStream pipedOutputStream = new PipedOutputStream();
final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);
AzureObjectStoreService objectStoreService =managedObjectStoreUtils.getObjectStoreService();
if (filesToZip.size() > 0) {
System.out.println("Files to zip "+ filesToZip.size());
CompletableFuture<Boolean> zipCreationFuture = CompletableFuture.runAsync(() -> {
LoggerHelper.logInfo(logger, "Inside createZIP file async function");
ZipOutputStream zipOutputStream = new ZipOutputStream(pipedOutputStream);
try {
for (String fileName : filesToZip) {
try {
BlobClient blobClient = objectStoreService.getBlobContainerClient().getBlobClient(fileName);
LoggerHelper.logInfo(logger, "Adding zipEntry for file : " + fileName);
final ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
byte[] buffer;
ByteArrayOutputStream output = new ByteArrayOutputStream();
buffer= output.toByteArray();
blobClient.getBlockBlobClient().download(output);
int len;
while ((len = buffer.length) > 0) {
zipOutputStream.write(buffer, 0, len);
}
zipOutputStream.closeEntry();
} catch (SdkClientException e) {
LoggerHelper.logExceptionWithMessage(logger, this.getClass().getName(), (Exception) e);
LoggerHelper.logError(logger, "Failed while getting s3 object");
}
}
zipOutputStream.finish();
} catch (IOException ex) {
LoggerHelper.logExceptionWithMessage(logger, this.getClass().getName(), (Exception) ex);
LoggerHelper.logError(logger, "Creating zip file failed");
} finally {
try {
zipOutputStream.close();
} catch (IOException e) {
LoggerHelper.logExceptionWithMessage(logger, this.getClass().getName(), (Exception) e);
LoggerHelper.logError(logger, "Failed to close the zip output stream");
}
}
LoggerHelper.logInfo(logger, "Completed createZIP file async function");
// return true;
}).handle((o, exception) -> {
LoggerHelper.logExceptionWithMessage(logger, this.getClass().getName(), (Exception) exception);
LoggerHelper.logError(logger, "Creating zip file failed");
return null;
});
Was able to do it this way. Please let me know if anyone has a better approach.
CompletableFuture.runAsync(() -> {
BlobClient blobClient = objectStoreService.getBlobContainerClient().getBlobClient(zipFileName);
BlobOutputStream blobOutputStream = blobClient.getBlockBlobClient().getBlobOutputStream();
try {
int nextData= pipedInputStream.read();
while (nextData!=-1) {
blobOutputStream.write(nextData);
nextData = pipedInputStream.read();
}blobOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

Upload file using org.apache.commons.net.ftp.FTPSClient

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

In uploading file they show connection is not open how to solve that

I am working in a java application into that i am using ftp to send file.
but when i send 20-30 file its show exception that is connection is not open
and the file is not send can any one help me. the cade that i am using to uplode file is below
public void uploadtxtFile(collectinfo myobj,String localFileFullName, String fileName, String hostDir)
throws Exception {
FTPClient ftpclient= DBConnection.connect();
File file = new File(localFileFullName);
if (!(file.isDirectory())) {
if (file.exists()) {
FileInputStream input = null;
BufferedInputStream bis=null;
try {
input = new FileInputStream(new File(localFileFullName));
if (input != null) {
hostDir = hostDir.replaceAll("//", "/");
logger.info("uploading host dir : " + hostDir);
boolean bool =false ;
logger.error("Replay of the ftp store file is 1111"+ ftpclient.getReplyCode());
try{
ftpclient.setBufferSize(1048576);
ftpclient.enterLocalPassiveMode();
logger.error("Replay of the ftp store file is 2222"+ ftpclient.getReplyCode());
if( ftpclient.isConnected()){
// here server timeout error is get
logger.error("here server timeout error is get");//new
bis = new BufferedInputStream(input);
logger.error("Replay of the ftp store file is 3333"+ ftpclient.getReplyCode());
bool = ftpclient.storeFile(hostDir, bis);
} else{
logger.error("here server timeout error is get");//new
bis = new BufferedInputStream(input);
logger.error("Replay of the ftp store file is 6666"+ ftpclient.getReplyCode());
ftpclient.enterLocalPassiveMode();
bool = ftpclient.storeFile(hostDir, bis);
}}finally{
bis.close();
input.close();
}
logger.error("Replay of the ftp store file is 4444 "+ ftpclient.getReplyCode());
if (bool) {
logger.info("Success uploading file on host dir :"+hostDir);
} else {
logger.error("file not uploaded.");
BackgroundService.pendingQueue.add(myobj);
}
} else {
logger.error("uploading file input null.");
}
} catch(Exception ex)
{
logger.error("Error in connection ="+ex);
BackgroundService.pendingQueue.add(myobj);
}finally {
ftpclient.logout();
ftpclient.disconnect();
}
} else {
logger.info("uploading file is not exists.");
}
}
}
into that DBConnection is a class that return FTPclient obj

Trouble with uploading a file from an applet to servlet

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

How do you upload a file to an FTP server?

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!

Categories