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
Related
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.
#PostMapping("/post")
public String write(#RequestParam("file") MultipartFile files, BoardDto boardDto) {
try {
String origFilename = files.getOriginalFilename();
String filename = new MD5Generator(origFilename).toString();
String savePath = System.getProperty("user.dir") + "\\files";
if (!new File(savePath).exists()) {
try {
new File(savePath).mkdir();
} catch(Exception e){
e.getStackTrace();
}
}
String filePath = savePath + "\\" + filename;
files.transferTo(new File(filePath));
FileDto fileDto = new FileDto();
fileDto.setOrigFilename(origFilename);
fileDto.setFilename(filename);
fileDto.setFilePath(filePath);
Long fileId = fileService.saveFile(fileDto);
boardDto.setFileId(fileId);
boardService.savePost(boardDto);
} catch(Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
if (!new File(savePath).exists()) {
^
constructor File.File(Long,String,String,String) is not applicable
Description: I am working on a file upload project. but it's not working. File is just entity class and It's someone else's code. the guy worked fine but I'm not
You can try to rewrite this code using Files API.
For example: ...if (Files.notExists(Paths.get(savePath))) {...
It looks like you create too many File objects.
You can upload a file to a Spring controller using logic as follows:
Basic HTML that sends a file to a /upload controller:
<p>Upload an image</p>
<form method="POST" onsubmit="myFunction()" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
<div>
Here is the controller:
// Upload a file.
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public ModelAndView singleFileUpload(#RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
String name = file.getOriginalFilename() ;
// DO something with the file.
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView(new RedirectView("photo"));
}
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
I have made a application where we can upload any file which will save in our local given directory. I want to modify it, i want to add a drop down (with multiple option i.e floor, store, section) for department. i.e if we want to upload a file in 'Store' folder, we can choose 'Store' option and the file will uploaded to the 'Store' folder. Same for 'Floor' and 'Section'.
I just need any example link for that.
i have made it in liferay.
import org.apache.commons.io.FileUtils;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class UploadDirectory extends MVCPortlet {
private final static int ONE_GB = 1073741824;
private final static String baseDir = "/home/xxcompny/workspace";
private final static String fileInputName = "fileupload";
public void upload(ActionRequest request, ActionResponse response)
throws Exception {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
long sizeInBytes = uploadRequest.getSize(fileInputName);
if (uploadRequest.getSize(fileInputName) == 0) {
throw new Exception("Received file is 0 bytes!");
}
File uploadedFile = uploadRequest.getFile(fileInputName);
String sourceFileName = uploadRequest.getFileName(fileInputName);
File folder = new File(baseDir);
if (folder.getUsableSpace() < ONE_GB) {
throw new Exception("Out of disk space!");
}
File filePath = new File(folder.getAbsolutePath() + File.separator + sourceFileName);
FileUtils.copyFile(uploadedFile, filePath);
}
}
JSP is here
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%# taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<portlet:defineObjects />
<portlet:actionURL name="upload" var="uploadFileURL"></portlet:actionURL>
<aui:form action="<%= uploadFileURL %>" enctype="multipart/form-data" method="post">
<select name="folder">
<option value="store">Store</option>
<option value="floor">Floor</option>
<option value="department">Department</option>
</select>
<aui:input type="file" name="fileupload" />
<aui:button name="Save" value="Save" type="submit" />
</aui:form>
i want the file will upload in the belonging folder.
I had somewhat similar task to upload files to specified folders, so following is bit modified code as per your requirement:
public void upload(ActionRequest request, ActionResponse response)
throws Exception {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
long sizeInBytes = uploadRequest.getSize(fileInputName);
if (sizeInBytes == 0) {
throw new Exception("Received file is 0 bytes!");
}
File uploadedFile = uploadRequest.getFile(fileInputName);
String sourceFileName = uploadRequest.getFileName(fileInputName);
/* selected folder from UI */
String paramFolder = uploadRequest.getParameter("folder");
byte[] bytes = FileUtil.getBytes(uploadedFile);
if (bytes != null && bytes.length > 0) {
try {
/* Create folder if doesn't exist */
File folder = new File(baseDir + File.separator + paramFolder);
if (!folder.exists()) {
folder.mkdir();
}
/* Write file to specified location */
File newFile = new File(folder.getAbsolutePath() + File.separator + sourceFileName);
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
fileOutputStream.write(bytes, 0, bytes.length);
fileOutputStream.close();
newFile = null;
} catch (FileNotFoundException fnf) {
newFile = null;
/* log exception */
} catch (IOException io) {
newFile = null;
/* log exception */
}
}
}
You can use the below code
String user_selected_option=request.getParameter("userSel")
realPath = getServletContext().getRealPath("/files");
destinationDir = new File(realPath+"/"+user_selected_option);
// save to destinationDir
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.