Java FTP Uploaded Images Corrupted - java

I'm trying to upload some files to a Local FTP server. The observable list has all the files, and are uploaded by looping the array
I'm using the commons-net-3.6.jar Library.
The Directory and everything get's created but the images uploaded are corrupted. Huge change in color (looks like an old static TV image with colors)
What am i doing wrong?
NOTE! Something I noticed was that the sizes of file's are the same in KB but differs slightly by bytes.
ObservableList<File> uploadFiles = FXCollections.observableArrayList();
FTPClient client = new FTPClient();
InputStream fis = null;
FTPConnection con = new FTPConnection();
con.readData(); //gets username and password
uploadFiles = Something.getFiles(); //Gets Files
try {
client.connect(con.getServerIp());
client.login(con.getUsername(), con.getPassword());
String pathname = getPathname();
client.makeDirectory(pathname);
for (int i = 0; i < uploadFiles.size(); i++) {
fis = new FileInputStream(uploadFiles.get(i));
String filename = uploadFiles.get(i).getName();
String uploadpath = pathname+"/"+filename;
System.out.println("Uploading File : " + uploadpath);
client.storeFile(uploadpath, fis);
}
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

Setting the file type to Binary did the Trick!
client.setFileType(FTP.BINARY_FILE_TYPE);

Related

unable to write Base64 image data on FTP server

I have encountered the problem to write Base64image data on FTP.
When I write it on local drive, The photo is appeared clearly.
But, When I write it on FTP server, it's appeared like spoiled images.
when I write it on local drive, it's shown like this enter image description here
I have attached the picture on FTP . enter image description here
Here is my code.
private static String testFilesDir = "C:\\Storage";
public String getIncidentPhotoByID(int incident_id, int photoId) {
String base64Image = null;
WebSSLClient client = new WebSSLClient();
Response response =client.createRequest(PropertiesUtil.getOracleCloudRestUrL() + "/mobile/platform/storage/collections/incident_photos_collection/objects/incident_462_03").get();
String jsonResponse = response.readEntity(String.class);
base64Image = jsonResponse;
FTPClient ftp = new FTPClient();
FileInputStream fis = null;
String filename = "incident_462_03";
String[] strings = base64Image.split(",");
String extension;
switch (strings[0]) {//check image's extension
case "data:image/jpeg;base64":
extension = "jpeg";
break;
case "data:image/png;base64":
extension = "png";
break;
default://should write cases for more images types
extension = "jpg";
break;
}
//convert base64 string to binary data
byte[] data1 = Base64.decodeBase64(strings[1]);
/*
String path = testFilesDir+"/"+filename+"."+ extension;
File file = new File(path);
try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
outputStream.write(data1);
} catch (IOException e) {
e.printStackTrace();
} */
try {
ftp.connect("link.myjpl.com");
ftp.login("user", "password");
String path = "Images/test/"+filename+"."+ extension;
OutputStream out1 = ftp.storeFileStream(path);
out1.write(data1);
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
}
return base64Image;
}
}
Try setting the fileType to FTP.BINARY_FILE_TYPE. Also as per the javadocs, to finalize the file transfer you must call completePendingCommand and check its return value to verify success.
See https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#storeFileStream(java.lang.String)

how to read and modify image file stored at FTP server using java

I want to make thumbanials of image stored on ftp server but i am getting following exception:
javax.imageio.IIOException: Can't read input file!
code :
String curr_input_img = null;
BufferedImage original_img = null;
String finalfolderpath = AppConstants.FTP_PATH + path;
String thumbailpath = finalfolderpath + "/thumbnail";
FTPClient client = new FTPClient();
try{
client.connect("188.148.12.58");
client.login("root", "admin123");
boolean result = client.changeWorkingDirectory(finalfolderpath);
FTPFile[] ftpfiles = client.listFiles();
if (result == true) {
client.makeDirectory("thumbnail");
for (FTPFile ftpfile : ftpfiles) {
curr_input_img = ftpfile.getName();
original_img = ImageIO.read(new File(curr_input_img)); // read original image
}
}
catch (Exception ex) {
System.out.println(ex);
}
You trying to read file from local file sistem.
You need to download file, edit it and upload back.
You can use FTPClient.retrieveFileStream() to get InputStream and then feed it to ImageIO.read

android ZipArchiveEntry giving java.nio.charset.MalformedInputException

I can unzip the 1st and 2nd entry of a zip file I am reading from the web, but then I get the MalformedInputException error. The zip file consists of unicode file names of mp3 files. I created the zip file that I placed on the web using Winzip (I tried both v11 and V18).
The mp3 files are all at the 'root' level in the zip file, i.e. not stored in subfolders.
I tried first with ZipInputStream. The last attempt (below) is with ArchiveInputStream. (I noticed that ArchiveInputStream didn't have a closeEntry() method like ZipInputStream - not that it made any difference).
The error always occurs on the line that gets the next entry.
while ((entry = (ZipArchiveEntry)zipStream.getNextEntry()) != null)
The code is
private void unizpMediaFile(String mediaDirectory, String zipFileURL) {
InputStream inputStream = null;
ArchiveInputStream zipStream = null;
ArchiveEntry entry = null;
try {
// make sure can write to (probably) sd card
File mediaFileDirectory = createMediaDirectory(mediaDirectory);
if (mediaFileDirectory == null)
return;
inputStream = getHttpInputStream(zipFileURL);
if (inputStream == null) {
return;
}
zipStream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,new BufferedInputStream(
inputStream) );
while ((entry = (ZipArchiveEntry)zipStream.getNextEntry()) != null) {
Log.i(TAG,"Entry:" + entry.getName());
if (entry.isDirectory()) {
if (false == new File( mediaFileDirectory.getAbsoluteFile()
+ File.separator + entry.getName()).mkdirs()) {
return;
}
} else {
OutputStream out = new FileOutputStream(mediaFileDirectory.getAbsoluteFile()
+ File.separator + entry.getName());
int size;
byte[] buffer = new byte[4096];
FileOutputStream outStream = new FileOutputStream(
mediaFileDirectory.getAbsoluteFile()
+ File.separator + entry.getName());
BufferedOutputStream bufferOut = new BufferedOutputStream(
outStream, buffer.length);
while ((size = zipStream.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, size);
}
bufferOut.flush();
bufferOut.close();
out.close();
Log.i(TAG,"Entry:" + entry.getName() + " closed.");
}
}
maintOpDetails.append(res.getString(R.string.load_complete));
updateLoadDetails(maintOpDetails.toString() );
} catch (FileNotFoundException e) {
Log.e(TAG, "unizpMediaFile" + e.toString());
storeErrorMessage(res.getString(R.string.error_reading_media_zip_file,
zipFileURL, e.toString()));
} catch (IOException e) {
Log.e(TAG, "unizpMediaFile" + e.toString());
storeErrorMessage(res.getString(R.string.error_reading_media_zip_file,
zipFileURL, e.toString()));
} catch (ArchiveException e) {
Log.e(TAG, "unizpMediaFile" + e.toString());
storeErrorMessage(res.getString(R.string.error_reading_media_zip_file,
zipFileURL, e.toString()));
}
finally {
if (inputStream != null){ try {inputStream.close();} catch (Exception e){} }
if (zipStream != null){ try {zipStream.close();} catch (Exception e){} }
}
}
private InputStream getHttpInputStream(String url) {
HttpResponse response;
InputStream is = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://" + url);
try {
response = httpClient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf;
buf = new BufferedHttpEntity(ht);
is = buf.getContent();
} catch (ClientProtocolException e) {
Log.e(TAG, "getHttpInputStream" + e.toString());
storeErrorMessage(res.getString(R.string.error_reading_file_at_url,
url, e.toString()));
} catch (ConnectTimeoutException cte) {
Log.e(TAG, "getHttpInputStream" + cte.toString());
storeErrorMessage(res.getString(R.string.connect_timetout_error, url));
} catch (IOException e) {
Log.e(TAG, "getHttpInputStream" + e.toString());
storeErrorMessage(res.getString(R.string.error_reading_file_at_url,
url, e.toString()));
}
return is;
}
From the log I get
I/LoadLanguageLessonService(3102): Entry:evet.mp3
I/LoadLanguageLessonService(3102): Entry:evet.mp3 closed.
I/LoadLanguageLessonService(3102): Entry:hay?r.mp3
I/LoadLanguageLessonService(3102): Entry:hay?r.mp3 closed.
E/LoadLanguageLessonService(3102): unizpMediaFilejava.nio.charset.MalformedInputException: Length: 1
(The cut/paste from the log to here caused the unicode filename values to be converted to the '?' you see above.)
I checked out various SO postings with no luck.
Any ideas?
Some followup
I modified my code to first download the zip file to my phone and then unzip it from there. No luck doing it that way either.
I also used the following code
ZipFile zipFile = null;
try {
zipFile = new ZipFile(zipFilename);
Enumeration<?> enu = zipFile.entries();
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
String name = zipEntry.getName();
long size = zipEntry.getSize();
long compressedSize = zipEntry.getCompressedSize();
Log.e(TAG, String.format("name: %-20s | size: %6d | compressed size: %6d\n",
name, size, compressedSize));
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
to list all the entries in the zip file and found that the unicode characters all show up as a small black diamond with a question mark inside (after cut/paste into SO the characters show up just with the ? mark).
I also downloaded AndroZip and WinZip for Android and viewed the zip file via both apps on my phone. Again the unicode file names were corrupted.
At this point I am stuck. I think I will shift gears and see about downloading the files one by one.

FTP download stops at file #146

I wrote this class (from examples) to download the header of all the files contained in a remote FTP folder. It works well, but when it approaches to download the file #146 it stops with a NullPointException. The file #146 exists and I can download it as a single file actually.
In the method remotePathLong contains all the remote folders written in a single line and spaced with the space character.
public void downloadHeader(String remotePathLong, String destPath, int bytes) {
String remotePath;
FTPFile[] fileList;
String[] fileNameList;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
int indice = 0;
int iP = 1;
File downloadFile;
String destFile;
String remoteFile;
byte[] bytesArray;
int bytesRead = -1;
while ((remotePath = getPath(remotePathLong, iP)) != null) {
System.out.println("Loading file list from the server.....");
fileNameList = ftpClient.listNames(remotePath);
for (String file : fileNameList) {
indice += 1;
System.out.println(indice + " - Downloading: " + file);
//Select files
destFile = destPath.concat(file);
downloadFile = new File(destFile);
outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
//Download remote file (from ftp)
remoteFile = remotePath.concat(file);
inputStream = ftpClient.retrieveFileStream(remoteFile);
bytesArray = new byte[bytes];
bytesRead = inputStream.read(bytesArray);
outputStream.write(bytesArray);
//Save into file
outputStream.close();
inputStream.close();
iP += 1;
}
}
} catch (IOException ex) {
} final{
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
catch (IOException ex1) {
System.out.println("Error: " + ex1.getMessage());
}
}
when it reaches bytesRead = inputStream.read(bytesArray), at the iteration #146 it gives the error. But if at the same iteration i reinitialize the connection it works.
Does anybody have a suggestion please?
It is possible your connection times out due to a network traffic or a file size that happens to be 146th.
Can you print the 146th file name and check its size. Also you can increase the FTP connection timeout period
ftpClient.setControlKeepAliveTimeout(300); // set timeout to 5 minutes

How do I download a image file from google webapp engine?

AppEngineFile AFE = new AppEngineFile(FILESYSTEM + alist.get(0).getPath());
BlobKey bk = FileServiceFactory.getFileService().getBlobKey(AFE);
if("image/jpeg".equals(alist.get(0).getContentType()) ){
resp.setContentType("image/jpeg");
}
resp.setHeader("Content-Disposition", "attachment; filename=\"" + alist.get(0).getTitle() + "\"");
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = null;
try {
file = fileService.getBlobFile(bk);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileReadChannel ch = null;
try {
ch = fileService.openReadChannel(file, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (LockException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] barray = new byte[MAXSIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ByteBuffer bb = ByteBuffer.wrap(barray);
int nRead;
while ((nRead=ch.read(bb)) != -1) {
for (int i=0; i < nRead; i++) {
try {
baos.write(barray[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
bb.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
resp.setContentLength(baos.size());
// resp.getOutputStream().write(baos.toByteArray()); // <= if I use it, this message, "Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.", is showed.
// out.print(baos); // <= if I use this, I can download a file but it is byte code.
baos.flush();
baos.close();
How do I fix whole this code for downloading an image file? because If I use Number 1, it make a error, which is "Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.", is showed." or if i use number 2, it looks fine but the type of stored file is byte code. This means is not image file.
Who can give me any idea or example?
I ran into this problem a while back. You cannot read files uploaded with the application. They are considered static application blobs and do not exist in any way accessible to your code.
Take a look here and notice that the only available option right now is BLOBSTORE.
If you want something to be readable by application code, it must be stored in the Blobstore or as a BlobProperty on an object in the Datastore (which is very inefficient, use the Blobstore if you can).

Categories