I have a folder inside resources folder where I want to upload media files. But I am constantly getting 'No file or directory found' error.
Here is what I have in my controller
#Autowired
ServletContext servletContext;
#RequestMapping(value = "/uploads", method = RequestMethod.POST)
public String insert(#RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
// String path = new
// ClassPathResource("/src/main/resources/uploads").getPath();
// FileCopyUtils.copy(file.getBytes(), new File(path));
String webappRoot = servletContext.getRealPath("/");
String relativeFolder = File.separator + "resources" + File.separator + "uploads" + File.separator;
System.out.println(webappRoot);
System.out.println(relativeFolder);
String filename = webappRoot + relativeFolder + file.getOriginalFilename();
FileCopyUtils.copy(file.getBytes(), new File(filename));
return "uploaded successfully";
}
And here is the error I am getting constantly
SEVERE: Servlet.service() for servlet [api] in context with path [/ek-service] threw exception
java.io.FileNotFoundException: /home/ekbana/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ek-service/resources/uploads/2.jpg (No such file or directory)
I have searched all over the web tried ResourceLoader and ClassPath. But still no success figuring it out.
Resources should be considered read-only, they are not accessible through the file system, but are embedded in the war/jar when you deploy an application.
You must write the file to a path on the file system that exists and that your application has write access to.
You can write to a temporary file, it has the benefit that you most certainly will have write access to it. Useful for testing until you figure out a permanent location to store the file, or for cases when permanent storage is not necessary. See example: http://www.mkyong.com/java/how-to-create-temporary-file-in-java/
Related
I'm developing a web application with spring boot. In application, I upload a file and copy to the local folder after that file absolute path is saved in the database. So I have file and I know where it is but I can't reach it in localhost. I know in spring has a static folder for static files but I don't want to copy a file because I will use this data in other applications.
For example:
Local file location: /Users/user/data/image.png
I want to reach like that: http://localhost:8080/data/image.png
Edit: I find the solution. I used MvcUriComponentsBuilder for this.
String url = MvcUriComponentsBuilder.fromMethodName(FileController.class,"serveFile",resource.getFilename()).build().toString();
it's return right value of controllers method.
Method:
#GetMapping("/files/{filename:.+}")
#ResponseBody
public ResponseEntity<Resource> serveFile(#PathVariable String filename) {
Resource file = storageService.loadAsResource(filename);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + file.getFilename() + "\"").body(file);
}
I think issue is with url you are using. Change it to:
#RequestMapping("/data/{filename:.+}")
this will work.
I am reading properties file to get a file path as below.
String result = "";
InputStream inputStream = null;
try {
Properties prop = new Properties();
String propFileName = "config.properties";
inputStream = GetPropertyValues.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
The properties file has the path specified like below.
configSettingsFilePath = C:\\\\ConfigSetting.xml
Now I get this below exception when I run my code saying file is not found.
Creating instance of bean 'configSettingHelper'
configSettingsFilePath = C:\ConfigSetting.xml
2017-09-18 14:47:00 DEBUG ConfigSettingHelper:42 - ConfigSettingHelper :: ConfigSetting File:configSettingsFilePath = C:\ConfigSetting.xml
javax.xml.bind.UnmarshalException
- with linked exception:
[java.io.FileNotFoundException: C:\Java\eclipse\eclipse\configSettingsFilePath = C:\ConfigSetting.xml (The filename, directory name, or volume label syntax is incorrect)]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
Instead of reading the path from properties file, if I directly use "C:\ConfigSetting.xml" in the code, it reads the file.
Can you please suggest what I should use in the properties file to specify the path?
Reading the file only fails when the .jar is running.
Running the app from within Netbeans is fine. (Different path)
Also, the path is coming from
URL resourceURL = MyClass.class.getResource("mydir/myfile.txt");
Printing out the path is perfect.
Also, a mypicture.gif in the very same directory loads fine:
ImageIcon mypicture = new ImageIcon(imageURL, description)).getImage();
even when running the .jar. IE: the actual path must be fine.
It is only a text file I try reading via
InputStream input = new FileInputStream(fileName);
is when it fails - and only if it is in the jar.
This is probably because C:\ is not on the classpath. You're using getClassLoader() which presumably returns a ClassLoader.
According to the docs for ClassLoader#getResource:
This method will first search the parent class loader for the
resource; if the parent is null the path of the class loader built-in
to the virtual machine is searched. That failing, this method will
invoke findResource(String) to find the resource.
That file is in the root of the drive, which is not going to be on the classpath or the path of the class loader built-in to the VM. If those fail, findResource is the fallback. It's unknown where findResource looks without seeing the implementation, but it doesn't appear to pay attention to the C:.
The solution is to move the properties file into your classpath. Typically, you'd put property files like this in the src/main/resources folder.
I need to save file from javabean or servlet, and I'm having trouble finding relative path, I tried:
(from servlet)
ServletContext servCont = this.getServletContext();
String contextPath = servCont.getRealPath(File.separator);
System.out.println("REAL PATH: "+ contextPath);
this gives me:
REAL PATH: E:\Web\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Saloni\
and project folder is:
E:\Web\Saloni
and from bean (bean is called Salon)
String path = Salon.class.getResource("Salon.class").getPath();
and got basically the same thing
/E:/Web/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Saloni/WEB-INF/classes/beans/Salon.class
If I just put file name into FileOutputStream file gets saved in eclipse workspace.
I read somewhere that I'm supposed to get to WEB-INF somehow but can't do that ..
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 am writting the code to upload a file using Spring's MultipartFile on server for that I have written following code
if(!partnersContentBean.getFile().isEmpty()){
MultipartFile file = partnersContentBean.getFile();
if(file.getOriginalFilename().endsWith(".jpeg")||file.getOriginalFilename().endsWith(".jpg")|| file.getOriginalFilename().endsWith(".gif")){
File dirPath = new File("//125.22.60.37/image/dev/cmt/");
if (!dirPath.exists()) {
dirPath.mkdirs();
}
URL url = new URL("http://125.22.60.37/image/dev/cmt/");
File destination = new File(url.toString());
file.transferTo(destination);
String url1 = request.getContextPath() + ApplicationConstants.imageUploadDirectory + file.getOriginalFilename();
System.out.println(url.getPath());
partnersContentBean.setPartnerImagename(file.getOriginalFilename());
partnersContentBean.setPartnerImagepath(destination.getPath());
}else
{
userModuleDetailBean.put("errorMessage", "File should be in type of jpg,Jpeg or GIF");
return new ModelAndView(new RedirectView("partnersAdd_CMT.htm"),"userModuleDetailBean",userModuleDetailBean);
}
}
but when I upload a file I get following exception java.io.FileNotFoundException: http:\125.22.60.37\image\dev\cmt (The filename, directory name, or volume label syntax is incorrect) dont know what path should i give to upload it
It looks like you're trying to transfer the uploaded file to another remote server (125.22.60.37). You can't do that - you can't represent an HTTP URL using a File object.
FileUpload is for storing the uploaded files to your local machine. Once there, you can worry about moving them to another remote server, but the two tasks are separate.