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();
Related
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.
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().
I am using Spring Framework's MultipartFile to allow a user to upload a picture to a profile. I've configured DispatcherServlet in a servlet initializer class that extends AbstractAnnotationConfigDispatcherServletInitializer. In that class, I've overridden the customizeRegistration() method as follows:
#Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("/tmp/practicewellness/uploads", 2097152, 4194304, 0));
}
The MultipartFile's transferTo() method calls for a file location in the filesystem where the uploaded file will be written temporarily. Can this location be anywhere? When I used the following location in the method:
profilePicture.transferTo(new File("tmp/practicewellness/" + employee.getUsername() + ".jpg"));
... I get the following error:
Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [C:\Users\kyle\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\work\Catalina\localhost\practicewellness\tmp\practicewellness\uploads] is not valid
So I can see that it's looking for this file location deep inside one of my Eclipse plugins. I don't understand why it looks there. When I look there, the "tmp" directory is not there. But regardless, is it okay for me to go into that plugin and create the directory there? Or is there a better way to smooth this out?
I've uploaded files using Spring mvc, but never used transferTo(), I just assume that your problem is due to "No existence of specified path" because there wont be a path ending with .jpg. Try it like this.
String path = "/tmp/practicewellness/";
File dirPath = new File(path);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
And then execute the transferTo() code.
Also do not set the path directly like you've done. Since you're doing it in spring, so I assume you want the folder to be in your Project path not the eclipse's metadata path. So change your path to this.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness/");
It will create a folder inside your Project's Webapp folder using mkdir. If you want to save differentiate the files for each user, you can create a folder for each user by using this below path.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness")+"/"+employee.getUsername()+"/";
I'm using this code
to upload an image from my android app to the user's google drive account.
But how can I modify the code to upload the image to folder named "myFolder"?
meaning to that folder is exist and if not - create such folder and then upload the image there.
What you need to do in order to upload a file to a specific folder is to add the folder's id to the file parents (ref Docs for file.insert).
So the full things you need to do are:
Find the folder in drive
Create the insert request
Add the parent id to the file insert
Execute the insert request
Code
Find the Folder
Here you can opt for 2 ways: loop all the folders or search for it.
Faster and less resource heavy is to search the folder by name; to do so it's simple:
//Search by name and type folder
String qStr = "mimeType = 'application/vnd.google-apps.folder' and title = 'myFolder'";
//Get the list of Folders
FileList fList=service.files().list().setQ(qStr).execute();
//Check that the result is one folder
File folder;
if (fList.getItems().lenght==0){
folder=fList.getItems()[0];
}
More info about the possible search parameters.
Create the insert request is as in the sample
File file = service.files().insert(body, mediaContent);
before executing it we need to set the parent
file.setParents(Arrays.asList(new ParentReference().setId(folder.getFolderId())));
In the end execute the request
file.execute();
I haven't tested the code so there might be some typo here and there.
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());