Android Can't Get Cached Image From File Path - java

We have a Cordova app. I am getting an Image passed to me which is saved in the cache.
I need to make a file from a string url:
File pictureFile = new File(fileURL)
However when I try to load that image file it keeps failing (file not found).
A sample of what I am passed is this:
file:///data/data/co.appname.app/cache/tfss-4cb94488-1843-4ad3-8d02-8802008c7186-1685720347.jpg
I have tried making the following urls and none work when I create a file
/data/data/co.appname.app/files/tfss-4cb94488-1843-4ad3-8d02-8802008c7186-1685720347.jpg
file:/data/data/co.appname.app/files/tfss-4cb94488-1843-4ad3-8d02-8802008c7186-1685720347.jpg
I also tried taking just the file name tfss-4cb94488-1843-4ad3-8d02-8802008c7186-1685720347.jpg and getting the cached directory directly and that didn't work either
String path = getFilesDir().getAbsolutePath() + tfss-4cb94488-1843-4ad3-8d02-8802008c7186-1685720347.jpg
That just ends up with /data/data/co.appname.app/files/tfss-4cb94488-1843-4ad3-8d02-8802008c7186-1685720347.jpg which still comes up null.
The image HAS to exist there though because we are uploading it to Twitter and Cordova is saving the image in the cache.
Can you advise what the issue might be?

I needed to call getCacheDir() not getFilesDir().

Related

java.io.IOException: File Not Found

I have uploaded a MultipartFile which is a video, and am trying to use capture a frame of it using some code. However, when it tries to open the file, it always gives the error java.io.IOException: File Not Found.
First I extract the multipart file to a normal file like so:
File convertedFile = new File(multipartFile.getOriginalFilename());
multipartFile.transferTo(convertedFile);
Then I set the file name of the video to the code to capture the frame like this:
"file://" + convertedFile.getName()
then it fails when it tries to create a URL out of the file name:
new URL(_videoFilename));
How can I make it find the file?
I haven't worked with MultipartFile but you can find this in the Javadoc
The file contents are either stored in memory or temporarily on disk.
In either case, the user is responsible for copying file contents to a
session-level or persistent store as and if desired. The temporary
storages will be cleared at the end of request processing.
Therefore, you certainly have to usetransferTo(File dest) to be able to handle your file on a determined place.

Where saving a file after being uploaded in Spring MVC

I have a form the allow user to upload file (jpg) with <form:input type="file"/> in SPring MVC
When I save the file I don't get any error from this code, but the file is not saved in C:\testTile.jpg:
public void salvaFoto(CommonsMultipartFile foto){
...
foto.transferTo(new File("C:\\testTile.jpg")); //This path is
//just a try, of course I should save the file in my Application url
...
}
My question is: how should I retrieve the application path in order to have the URI for my File object?
I tried with ServletContext.getContextPath(), but the file wasn't saved as well.
Thank you
When I save the file I don't get any error from this code, but the
file is not saved in C:\testTile.jpg:
The problem is as you don't have enough permission to write to that path.
Run your application in debug mode and mark breakpoint before this call and check the path that it is showing. You will be able to debug the solution by your own using debug mode.
This might help if you want to store inside WEB-INF/../ folder of your application
String path = getServletContext().getRealPath("WEB-INF/../");
File file = new File(path);
String fullPathToYourWebappRoot = file.getCanonicalPath();

Struts2: How to store images outside of the webapp and save its path to the db?

Until now I did saving image into the webapp directory and its path into database.
But now am trying to save the image outside of the webapp so that if I deploy my new war files then my old files folder will not be deleted.
From my below code my image file is correctly saving into the specified folder outside of the webapp but i don't know how to retrieve that image into my jsp page.
I tried like this
<img src="www.myproject.com/struts2project/files/smile.jpg/>"
but this is wrong. I am not getting my image to be display into my jsp page.
Below code is working fine for uploading image into absolute path but my problem is how to retrieve that image?
`fileSystemPath= "/files";
try{
File destFile = new File(fileSystemPath, thempicFileName);
FileUtils.copyFile(thempic, destFile);
String path=fileSystemPath+"/"+thempicFileName;
theme=dao.getThemeById(themId);
theme.setThemeScreenshot(path);
theme.setThemeName(theme.getThemeName());
theme.setThemeCaption(theme.getThemeCaption());
dao.saveOrUpdateTheme(theme);
}catch(IOException e){
e.printStackTrace();
return INPUT;
}`
Kindly help me...
I hope I'm being clear on what I need, let me know if I am not and I'll try to explain in another way.
As you say . . . this question describes what you need to do. I guess what you need to know is how to best achieve this with struts 2. Here's what's going on.
In your tag:
That url is being routed to your struts 2 application. Correct? The context is "struts2project".
One of the solutions offered by the referenced question is to use Tomcat's ability to serve static requests and configure tomcat to know about this other document root that holds your images. I think this is a great solution.
If you want to keep it inside of struts2, I think you're best option is to use a dedicated "image streaming from that other place" action that get's an InputStream to the image, then uses the Struts2 Stream Result result type. That result type lets you specify an adhoc InputStream. It also helps you set the appropriate headers. Note, the header values on that documentation page are for downloading the file, so you don't want those values. They would force the browser to open a save as dialog for the image, I think.
You are already using absolute paths, just use a location outside of your web application:
String destinationDir = "/path/to/my/directory/";
File file = new File(destinationDir + item.getName());

What is the correct path for Toolkit.getImage()?

I need to upload an image file and generate a thumbnail for the uploaded file in my JSF webapplication. The original image is stored on the server in /home/myname/tomcat/webapps/uploads, while the thumbnail is stored in /home/myname/tomcat/webapps/uploads/thumbs. I'm using the thumbnail generator class I copied from philreeve.com.
I have successfully uploaded the file with help from BalusC. But using Toolkit.getImage(), I can't access the image.
I used the uploaded file's absolute path, like so:
inFilename = file.getAbsolutePath();
The relevant code from the thumbnail generator is:
public static String createThumbnail(String inFilename, String outFilename, int largestDimension) {
...
Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
return "Error loading file: \"" + new File(inFilename).getAbsolutePath() + "\"";
}
...
}
Since I am already using the absolute path, I don't understand why it is not working. I have also used the following values for inFilename, but I always get the "Error loading file...".
/home/myname/tomcat/webapps/uploads/filename.ext
/uploads/filename.ext
But I did check the directory, and the image is there. (I uploaded using /home/myname/tomcat/webapps/uploads/filename.ext, and it works.) What is the correct path for the image in that directory? Thank you.
Update
I got the code to work by using:
Image inImage = ImageIO.read(new File(inFilename));
I still don't understand why Toolkit.getImage() does not work though.
Are you sure it's a JPEG file? Use an image viewer to make sure nothing bad happened to the file during upload (or that it was an image to begin with).
Also, use new File(inFilename).exists() to make sure the path is correct. I also suggest to print new File(inFilename).getAbsolutePath() in error messages because relative paths can hurt you.
That said, the rest of the code looks correct.
The problem is that Toolkit.getImage() does not return the image immediately. The issue is well-described in this bug report, a relevant extract of which is here:
This is not a bug. The submitter is not properly using the asynchronous
Image API correctly. He assumes that getImage loads all of the image's bits
into memory. However, it is well documented that the actual loading of
bits does not take place until a call to Component.prepareImage or
Graphics.drawImage. In addition, these two functions return before the
Image is fully loaded. Developers are required to install an ImageObserver
to listen for notification that the Image has been fully loaded. Once they
receive this notification, they can repaint the Image.
I found that the answer to this question works well:
Image image = new ImageIcon(this.getClass().getResource("/images/bell-icon16.png")).getImage();

Loading files within android

Android seems to make life pretty easy for loading resources of certain types. Once I leave the beaten path a little bit, it seems less helpful. I can load in images, sounds and other objects from the assets folder if and only if they are of certain types. If I try to load a binary file of my own format, I get a less than helpful 'file not found' exception, even though listing the directory shows that it is clearly there.
I've tried using the following methods to read a binary file of a custom format from the assets directory:
File jfile = new File("file://android_asset/"+filename); //tried to get the URI of the assets folder
JarFile file = new JarFile("assets/"+filename); //tried assuming the assets folder is root
fd = am.openNonAssetFd( filename); //tried getting my file as an non asset in the assets folder (n.b. it is definitely there)
fs = am.open(filename, AssetManager.ACCESS_BUFFER); //tried loading it as an asset
I'm thinking that there's something fundamental about android file I/O that I don't understand yet. The documentation for asset management seems incomplete and there must be some reason for deliberately making this unintuitive (something to do with security?). So, what's the fool proof, canonical way of loading a binary file of my own format within an android app?
UPDATE:
I tried file:///android_asset/ but still no joy.
String fullfilename = "file:///android_asset/"+filename;
File jfile = new File(fullfilename);
if (jfile.exists())
{
return new FileInputStream(jfile);
}
else
{
return null; //the file does exist but it always says it doesn't.
}
Are there any permissions for the file or in the project manifest that I need?
Thanks
I think the best way to load a file from the Assets folder would be to use AssetManager.open(String filename) - this gives you back an InputStream which you can then wrap in a BufferedInputStream and otherwise call read() to get the bytes. This would work regardless of the file type. What kind of problems have you had with this approach specifically?
I think you have left out the slash as in
File jfile = new File("file:///android_asset/"+filename);
There's three forward slashes, not two. :)
For me the solution was to uninistall the application, clean the project in Eclipse and run it again. The problem was Android couldn't find the new files I put in the asset folder.
I ended up reading this question so I hope this can be helpful to someone else.

Categories