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)
Related
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);
I'm writing a program to download a PDF file from server. I'm using some program given here Download file by passing URL using java code, this solution works fine for the sample URL provided in the first answer, but not for PDF, I'm replacing just the URL. Below is my code.
import java.io.*;
import java.net.*;
public class FileDownloadTest {
final static int size = 1024;
public static void fileUrl(String fAddress, String localFileName, String destinationDir) {
// localFileName = "Hello World";
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL url;
byte[] buf;
int byteRead, byteWritten = 0;
url = new URL(fAddress);
outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));
uCon = url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((byteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, byteRead);
byteWritten += byteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void fileDownload(String fAddress, String destinationDir) {
int slashIndex = fAddress.lastIndexOf('/');
int periodIndex = fAddress.lastIndexOf('.');
String fileName = fAddress.substring(slashIndex + 1);
if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < fAddress.length() - 1) {
fileUrl(fAddress, fileName, destinationDir);
} else {
System.err.println("path or file name.");
}
}
public static void main(String[] args) {
String fAddress = "http://singztechmusings.files.wordpress.com/2011/09/maven_eclipse_and_osgi_working_together.pdf";
String destinationDir = "D:\\FileDownload";
fileDownload(fAddress, destinationDir);
}
}
Here, This pdf has 73 pages, and in my folder, it is download as a PDF of 1KB, when opened in Acrobat Reader, it says that the file might be corrupted.
I've also tried the code provided here https://dzone.com/articles/java-how-save-download-file, but the result is same.
please let me know how can I fix this.
Thanks
If you check the downloaded file content, you can see it is html. The server is redirecting the original request to https url. Use url https://singztechmusings.files.wordpress.com/2011/09/maven_eclipse_and_osgi_working_together.pdf instead.
Or use http client with automatic redirect handling, ala http-commons
You define a Variable size = 1024 and use this to define your Buffer.
So logically you can only write 1 KB into it.
But if the input Stream reads more at once it will be lost ... So change your Buffer size to a value which would be able to contain most documents or try to determine the necessary size
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
I have an image being sent to me through a JSON string. I want to convert that string into an image in my android app and then display that image.
The JSON string looks like this:
"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."
Note: I truncated the string with a ...
I've got a function that (I think) converts the string into an image. Am I doing this right?
public Bitmap ConvertToImage(String image){
try{
InputStream stream = new ByteArrayInputStream(image.getBytes());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
return bitmap;
}
catch (Exception e) {
return null;
}
}
Then I try to display it on my android activity like this
String image = jsonObject.getString("barcode_img");
Bitmap myBitmap = this.ConvertToImage(image);
ImageView cimg = (ImageView)findViewById(R.id.imageView1);
//Now try setting dynamic image
cimg.setImageBitmap(myBitmap);
However, when I do this, nothing shows up. I don't get any errors in the logcat. What am I doing wrong?
Thanks
I'm worried about that you need to decode only the base64 string to get the image bytes, so in your
"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."
string, you must get the data after data:image\/png;base64,, so you get only the image bytes and then decode them:
String imageDataBytes = completeImageData.substring(completeImageData.indexOf(",")+1);
InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));
This is a code so you understand how it works, but if you receive a JSON object it should be done the correct way:
Converting the JSON string to a JSON object.
Extract the String under data key.
Make sure that starts with image/png so you know is a png image.
Make sure that contains base64 string, so you know that data must be decoded.
Decode the data after base64 string to get the image.
InputStream stream = new ByteArrayInputStream(image.getBytes());
should be changed to
InputStream stream = new ByteArrayInputStream(Base64.decode(image.getBytes(), Base64.DEFAULT));
Refer http://developer.android.com/reference/android/util/Base64.html for details on how to do Base64 decoding.
Disclaimer: I have not checked for syntax, but this is how you should do it.
Here is the working code that converts the Base64 encoded inputStream and writes it to the disk.
I spent a few time to make it work correctly. So I hope this helps other developers.
public boolean writeImageToDisk(FileItem item, File imageFile) {
// clear error message
errorMessage = null;
FileOutputStream out = null;
boolean ret = false;
try {
// write thumbnail to output folder
out = createOutputStream(imageFile);
// Copy input stream to output stream
byte[] headerBytes = new byte[22];
InputStream imageStream = item.getInputStream();
imageStream.read(headerBytes);
String header = new String(headerBytes);
// System.out.println(header);
byte[] b = new byte[4 * 1024];
byte[] decoded;
int read = 0;
while ((read = imageStream.read(b)) != -1) {
// System.out.println();
if (Base64.isArrayByteBase64(b)) {
decoded = Base64.decodeBase64(b);
out.write(decoded);
}
}
ret = true;
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
errorMessage = "error: " + sw;
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("Cannot close outputStream after writing file to disk!" + sw.toString());
}
}
}
return ret;
}
/**
* Helper method for the creation of a file output stream.
*
* #param imageFolder
* : folder where images are to be saved.
* #param id
* : id of spcefic image file.
* #return FileOutputStream object prepared to store images.
* #throws FileNotFoundException
*/
protected FileOutputStream createOutputStream(File imageFile) throws FileNotFoundException {
imageFile.getParentFile().mkdirs();
return new FileOutputStream(imageFile);
}
I want to develop an application in android in which I need to capture image and convert that image to string and write that string in txt file and send it to server where server reads that file and convert that string to image again...
now i have done with image taking part and converting that image into string and writing that string to txt file.
but when am try to read that file and convert that string into the image it's not working...
Code for converting image into string is
File imageFile = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image = stream.toByteArray();
imgstr = Base64.encodeToString(image, 0);
Code for writing that into file is
File file = new File("new.txt");
FileWriter w = new FileWriter("/sdcard/new/new.txt");
BufferedWriter out = new BufferedWriter(w);
out.write(data);
out.flush();
out.close();
And code for read that file and convert that string to image again is
FileInputStream fstream = new FileInputStream("/sdcard/new/new.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
ArrayList list=new ArrayList();
while ((strLine = br.readLine()) != null)
{
list.add(strLine);
}
Iterator itr;
for (itr=list.iterator(); itr.hasNext(); )
{
String str=itr.next().toString();
StringBuffer sb=new StringBuffer(str);
int length=sb.length();
String imageDataString = sb.substring(0, length);
byte[] decodedString = Base64.decode(imageDataString, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
FileOutputStream imageOutFile = new FileOutputStream("/sdcard/new/android.jpg");
imageOutFile.write(decodedString);
imageOutFile.close();
System.out.println("File converted");
but its not converting that string into image
please tell me solution for it...
if all you need is uploading files via ftp from android to web server, this will do the trick (working from froyo up - BUT you must import apache commons and install a copy inside your "src" folder):
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import android.util.Log;
public class FtpFileUp implements Runnable {
private final String TAG = "FTPfile";
boolean flagFTPOK = false;
String fileName, fileDirSubLocalName, fileDirSubRemoteName;
String fileDirName = NavigationActivity.fileDirName;
FtpFileUp (String fileNameIn, String fileDirSubLocalNameIn, String fileDirSubRemoteNameIn) {
fileName = (String) fileNameIn;
fileDirSubLocalName = (String) fileDirSubLocalNameIn;
fileDirSubRemoteName = (String) fileDirSubRemoteNameIn;
}
FtpFileUp (String fileNameIn) {
String fileDirSubNameIn = "";
fileName = (String) fileNameIn;
fileDirSubLocalName = (String) fileDirSubNameIn;
fileDirSubRemoteName = (String) fileDirSubNameIn;
}
FtpFileUp (String fileNameIn, String fileDirSubNameIn) {
fileName = (String) fileNameIn;
fileDirSubLocalName = (String) fileDirSubNameIn;
fileDirSubRemoteName = (String) fileDirSubNameIn;
}
#Override
public void run() {
String ftpConnectString = "ftp.yourdomain.com";
if (fileDirSubRemoteName != "") fileDirSubRemoteName += "/";
if (fileDirSubLocalName != "") fileDirSubLocalName += "/";
FTPClient ftpCli = new FTPClient();
try {
FileInputStream fis = new FileInputStream(fileDirName+"/"+fileDirSubLocalName+fileName);
ftpCli.connect(ftpConnectString);
ftpCli.login("user", "password");
Log.i(TAG, "ok ftp "+ftpCli.getDataConnectionMode());
ftpCli.storeFile("/"+fileDirSubRemoteName+fileName, fis);
fis.close();
flagFTPOK = true;
} catch (Exception except) {
Log.i(TAG, "ftp up FAIL "+except);
}
}
}
which you would call using the following code (encapsulated by TRY CATCH)
Thread ftpThread01 = new Thread(new FtpFileUp("fileName", "", "/www/android/imgUpload"));
ftpThread01.start();
NOTE: as you can see, there are 2 alternative constructors that you may use to automatize your ftp, by storing default locations. they may be removed with no harm.