I am trying to write an Android application that takes a user image and uploads it to a server. I can view the image on my phone, but cannot view the image when I copy the file from the server. I am using the Apache commons library to do FTP uploads. The file appears, and the size is correct, but it cannot be opened.
public static void uploadImage(Bitmap bitmap,String path)
{
String filePath="RENT/images/capture/TESTFILE.jpg";
try
{
FTPClient client = new FTPClient();
client.connect("MY IP");
client.login("USER", "PWD");
client.enterLocalPassiveMode();
Log.i("aaa","connected: "+client.isConnected());
Log.i("aaa","going to addr: "+client.getRemoteAddress());
FileInputStream fis = new FileInputStream(bitmapToFile(bitmap));
Log.i("aaa","2-starting to upload file");
client.storeFile(filePath, fis);
fis.close();
client.logout();
Log.i("aaa","3-file upload complete");
}
catch (IOException e) {
e.printStackTrace();
}
}
public static File bitmapToFile(Bitmap bitmap) throws IOException
{
File outputDir = con.getCacheDir();
File outputFile = File.createTempFile("testFile", ".jpg", outputDir);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 90, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(bitmapdata);
fos.flush();
fos.close();
return outputFile;
}
}
I found a solution. The entire (working) code is below: (requires apache libraries).
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.client.ClientProtocolException;
I used version 4.0.1 for this project.
public static void uploadImage(String path)
{
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("IP");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
ftpClient.setSoTimeout(10000);
ftpClient.enterLocalPassiveMode();
if(ftpClient.login("USR", "PWD"))
{
Log.i("aaa","Path: "+path);
File sFile=new File(path);
if(!sFile.exists())
Log.i("aaa","file not exist");
FileInputStream fs= new FileInputStream(sFile);
String fileName = "xxx.jpg";
Boolean result = ftpClient.storeFile("RENT/images/capture/" + fileName, fs);
Log.i("aaa","result: "+result);
if(result)
new File(path).delete();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I needed to set both the ftpClient.fileType and the ftpClient.setFileTransferMode to binary filetype.