How to change getRealPath("/") path from .metadata to WEB-INF - java

I am uploading image files from application, now I want to save them in WEB-INF, but eclipse is saving it in .metadata folder .metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps.
Please let me know who can I get the path to WEB-INF3
#RequestMapping(value = "/admin/productInventory/addProduct", method = RequestMethod.POST)
public String addProduct(#ModelAttribute("product") Product product,HttpServletRequest request) {//httservlet- aswe need to use that toget thesessionpath
productDao.addProduct(product);
/////add image
MultipartFile productImage= product.getProductImage();
String rootDirectory= request.getSession().getServletContext().getRealPath("/"); //C:\Users\Avinash Kharche\ECommerce_Spring_Neon\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\emusicStore\
path =Paths.get(rootDirectory + "\\WEB-INF\\resources\\images\\" + product.getProductId()+".png");
//path =Paths.get("C:\\Users\\Avinash Kharche\\ECommerce_Spring_Neon\\emusicStore\\src\\main\\webapp\\WEB-INF\\resources\\images\\" + product.getProductId()+".png");
if(productImage!=null && !productImage.isEmpty()){
try{
productImage.transferTo(new File(path.toString()));
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException("Product image saving failed",e);
}
}
/////
return "redirect:/admin/productInventory";
}
I dont want to use commented path
(//path =Paths.get("C:\Users\Avinash Kharche\ECommerce_Spring_Neon\emusicStore\src\main\webapp\WEB-INF\resources\images\" + product.getProductId()+".png");)
Please let me know any solution. Thanks

Here is the solution:
#RequestMapping(value = "/admin/productInventory/addProduct", method = RequestMethod.POST)
public String addProductPost(#ModelAttribute("product") Product product, HttpServletRequest request) {
productDao.addProduct(product);
MultipartFile productImage = product.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
path = Paths.get(rootDirectory + "/WEB-INF/resources/images/" + product.getProductId() + ".png");
if (productImage != null && !productImage.isEmpty()) {
try {
productImage.transferTo(new File(path.toString()));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Product image saving failed", e);
}
}
return "redirect:/admin/productInventory";
}
Change path from:
path =Paths.get(rootDirectory + "\\WEB-INF\\resources\\images\\" + product.getProductId()+".png");
To
path = Paths.get(rootDirectory + "/WEB-INF/resources/images/" + product.getProductId() + ".png");
Make sure you do the same for edit and delete functions. I had the same problem. With your version, it worked on windows but on Mac, I had to change the path as shown above

Related

Decide where to store uploade file ( path )

I have an app where user can upload file with additional info about it, such as description.
Now what i do is:
predefine the PATH where the files are stored ( so for example for server it will be at /files/ or for AWS url to aws )
user uploads file
file is saved, at location PATH/userId/uploaded file name
service that saves file returns whole path
the informations about file ( including path where it was stored ) is stored in DB.
So smth like this:
#Service
public class DiskSaveFileService implements SaveFileService {
#Value("${file.path}")
private String path;
#Override
public String saveFile(String fileName, byte[] bytes) {
Path targetLocation = Paths.get(path + "/" + fileName);
try {
Files.createDirectories(targetLocation.getParent());
Files.write(targetLocation, bytes);
} catch (IOException e) {
throw new SaveFileException("Saving file failed", e);
}
return targetLocation.toString();
}
#Override
public boolean safeDeleteFile(String fileName) throws SaveFileException {
Path targetLocation = Paths.get(path + "/" + fileName);
try {
Files.delete(targetLocation);
} catch (IOException e) {
return false;
}
return true;
}
}
And service:
UserEntity user = userUtilService.getLoggedUser();
String fileName = file.getOriginalFilename();
String path = user.getId() + "/" + fileName;
try{
String location = saveFileService.saveFile(path, uploadedFile.getBytes());
FileEntity fileEntity = new FileEntity();
fileEntity.setPath(location);
....
fileRepository.save(fileEntity);
} catch (UsernameNotFoundException | SaveFileException | IOException e) {
deleteFile(path);
throw new RecipeServiceException("Error creating recipe!", e);
}
However if user wanted to upload two separate files, that happens to have same name, this would overwritte them, as both files would be saved in the same path.
What is the best way to determine where exactly to store path? I first wanted to save the file as
PATH/userId/id of entity/name of the file
However in that case i would need to save info about file to database, then save the file ( so i will have generated ID of row ), and then update entity of location. So i would have extra database hit.
What are some best ways to decide the path then? Methods that would actually makes sense.

How to copy video or image file from one location into another using media store api for android 11

public boolean moveFilesToSentPath(Context context, String type, String filePath, String fileName) {
String folderPath = getFolderPath(type);
File dir;
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File(Environment.DIRECTORY_MOVIES *//*+ "/" + fileName*//*);
}else {*/
dir = new File(this.context.getFilesDir().toString() + "/" + folderPath); // }
if (!dir.exists()) {
dir.mkdirs();
File nomediaFile = new File(dir.getAbsoluteFile(), ".nomedia");
try {
if (!nomediaFile.exists()) {
nomediaFile.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File from = new File(filePath);
File to = new File(dir + "/" + fileName);
Log.v(TAG, "moveFilesToSentPathFrom= " + from);
Log.v(TAG, "moveFilesToSentPathTo= " + to);
if (from.exists()) {
try {
FileUtils.copyFile(from, to);
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
I want to copy video file from its original location to my own created destination i.e. like (Environment.DIRECTORY_MOVIES + "/" + "video" + "/"+fileName) and then access the file from destination. And also plz elaborate the media store api usage for saving file at specific location
The above code is for api level lower than 30, but need solution for android 11 api level 30 as we can't access storage due to security reasons but instead they provide with media store api, I don't have much idea with media store api. Thanks in advance for the help.

Load Image/Files from Spring Boot Rest api To the Android front end

This is my controller end point that will take the request from the frontend with the filename and using that filename image/file shall be returned. It works fine while testing on postman but I have no idea how to load images/files from this end point in android.
GetMapping("downloadFile/{fileName}")
#PreAuthorize("hasRole('ADMIN') or hasRole('MODERATOR') or hasRole('USER')")
public ResponseEntity<Resource> downloadFile(#PathVariable String fileName, HttpServletRequest request) {
Resource resource = fileStorageService.loadFileAsResource(fileName);
//System.out.println(resource);
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace();
}
if (contentType == null) {
contentType = AppConstants.DEFAULT_CONTENT_TYPE;
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION,
String.format(AppConstants.FILE_DOWNLOAD_HTTP_HEADER, resource.getFilename()))
.body(resource);
}
And My service for this looks like..
public Resource loadFileAsResource(String fileName) {
try {
//Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Path filePath= this.fileStoragePath.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
throw new FileStorageException(AppConstants.FILE_NOT_FOUND + fileName);
}
} catch (MalformedURLException ex) {
throw new FileStorageException(AppConstants.FILE_NOT_FOUND + fileName, ex);
}
}
I need to load image/files from here to the android frontend.
Picasso is the option to do this. just load your images with the resource you receive from server...

Upload and get image on Tomcat embed server(Heroku Deploy) Spring MVC

I'm new to Spring(Spring MVC).I have a task to save an image, upload it and save it to the server (embed Tomcat server). I implemented the following code.
#PostMapping(value = "/upload")
public String upload(HttpServletRequest request, #RequestParam("avatar") MultipartFile multipartFile, #ModelAttribute("movie") Movie movie) {
String filePath = request.getSession().getServletContext().getRealPath("/avatars/");
try {
multipartFile.transferTo(new File(filePath, multipartFile.getOriginalFilename()));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
movie.setUrlAvatar(filePath + multipartFile.getOriginalFilename());
movieService.createMovie(movie); // Save to DB
return "redirect: home";
}
And my view
<c:forEach var="item" items="${movies}">
<li>
<a href='<c:url value= "/movie/${item.getId()}"></c:url>'><img
alt="${item.getUrlAvatar()}" src='<c:url value="${item.getUrlAvatar()}"></c:url>'>
</a>
</li>
</c:forEach>
I even try src='<c:url value="file:///${item.getUrlAvatar()}"></c:url>' and it not working !!!
Where am I wrong when I cannot get the pictures out. Is there any way to get the images out ??
Can you suggest me a way to save images and remove images (I don't want to save to the Database now)?
Thank to all you!
Problem at
movie.setUrlAvatar(getBaseURL(request) + "/avatars/" + multipartFile.getOriginalFilename());
with
// get base URL
public String getBaseURL(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath();
}
And I have to do this
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdirs();
}
File serverFile = new File(dir.getAbsolutePath() + File.separator + avatarNewName);
Then multipartFile.transferTo(serverFile);
I found this at here

System.getProperty("user.home") returns /root when running on Tomcat

I am developing my application in Ubuntu. I have one Java web Spring MVC application. In that I have a controller. The client can upload a file (posting through AngularJS). In the controller, I am getting the file and copying to a specific location.
Here is my controller
#RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
#ResponseBody
public String UploadFile(HttpServletRequest request,HttpServletResponse response) {
SimpleDateFormat sdf = new SimpleDateFormat("MM_dd_yyyy_HHmmss");
String date = sdf.format(new Date());
String fileLoc = null;
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext()) {
MultipartFile mFile = mRequest.getFile(itr.next());
String fileName = mFile.getOriginalFilename();
String homePath=System.getProperty("user.home");
String separator=File.separator;
fileLoc = homePath + separator + "myapp" + separator + "file-uploads" +
separator + date + "_" + fileName;
System.out.println(fileLoc);
try {
File file = new File(fileLoc);
// If the directory does not exist, create it
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileCopyUtils.copy(mFile.getBytes(), file);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
return fileLoc;
}
But when I deploy it in tomcat server and run, the file is getting created in root.
When I print the value of fileLoc, it shows
/root/myapp/file-uploads/01_16_2014_000924_document.jpg
I added a main method in the controller.
public static void main(String[] args) {
String homePath=System.getProperty("user.home");
String separator=File.separator;
System.out.println("Home Path: " + homePath);
System.out.println("Separator: " + separator);
}
When I run this as Java Application, I am getting proper output
Home Path : /home/shiju
Separator : /
Why it's giving root when running on Tomcat?
If you are executing the application with the root user then it is obvious that /root/ will be returned in the user.home property.

Categories

Resources