How to upload file in relative directory - java

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

Related

Why Post controller to upload a file is not working

#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"));
}

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

Why File uploading by custom java tag returns null

I am trying to write a java custom tag to uploaded file.But while uploading file it returns null as output.any help can appreciated
Tag Handler class:
public class SavePostTag extends SimpleTagSupport {
boolean isMultiPart;
public void doTag() throws JspException, IOException {
PageContext ctx = (PageContext)getJspContext();
HttpServletRequest request = (HttpServletRequest)ctx.getRequest();
try {
final Part tmpFile = request.getPart("file");
String fileName = request.getHeader("content-disposition");
ir.mahdiii.entity.File file = new ir.mahdiii.entity.File(Constant.repositoryPath + fileName, UrlGenerator.getInstance().generateRndUrl());
DbManager.getInstance().saveFileInfo(file);
FileOutputStream fileOutputStream = new FileOutputStream(file);
int tmp = 0;
FileInputStream fileInputstream = (FileInputStream)tmpFile.getInputStream();
while ((tmp = fileInputstream.read(new byte[1024])) != -1) {
fileOutputStream.write(tmp);
}
fileOutputStream.close();
} catch (ServletException | ClassNotFoundException | SQLException | NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getJspContext().getOut().write("SUCCESS");
}
JSP file:
<c:if test="${param.status eq 'success'}">
<j:savepost/>
</c:if>
<div class="row">
<form action="/web/?page=admin&status=success" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
</div>
but at the line final Part **tmpFile = request.getPart("file"); it returns null.
any idea?

Uploading multiple files using jsp & servlets [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am currently working on a dynamic web application that I want the user to be able to upload multiple files at once for the application to use. I don't know how many files the user may upload at once; it could be 2 or it could 100+ files. I am new to JSP dynamic web applications and I have started with a single upload file but I am not really sure where to go from here. I've looked at few examples searching but I haven't been able to find exactly what I was looking for. This is what I have so far:
Servlet:
package Servlets;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (isMultipart)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
String abc = item.getString();
out.println("<br><br><h1>"+abc+"</h1><br><br>");
}
}
}
catch (FileUploadException e)
{
out.println(e);
}
catch (Exception e)
{
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
}
}
.JSP File:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<p><input type="file" name="dataFile" id="fileChooser" />
<input type="submit" value="Upload" multiple="multiple" /></p>
</form>
I am looking for a way to upload multiple files instead of just one and show them in a list.
Check the FileUPload Using Servlet 3.0
It has a working code for uploading Single File Using Servlet3.0 As you can see code is now much simplified . And there is no dependancy on apache Library.
just use below index.html
<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName" multiple/>
<br>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
Only change here is I have used multiple attribute for input type File
Oh... At the first glance, looks like a simple mistake. multiple is an attribute of file input, not of the submit button.
i have upload multiple files using jsp /servlet.
following is the code that i have used.
<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
on the other hand server side. use following code.
package com.abc..servlet;
import java.io.File;
---------
--------
/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.sendRedirect("../jsp/ErrorPage.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;
String path1 = filePathUpload;
String filename = null;
File path = null;
FileItem item=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String FieldName = "";
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
if (fieldname.equals("description")) {
description = item.getString();
}
}
if (!item.isFormField()) {
filename = item.getName();
path = new File(path1 + File.separator);
if (!path.exists()) {
boolean status = path.mkdirs();
}
/* START OF CODE FRO PRIVILEDGE*/
File uploadedFile = new File(path + Filename); // for copy file
item.write(uploadedFile);
}
} else {
f1 = item.getName();
}
} // END OF WHILE
response.sendRedirect("welcome.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
images.jsp
choose files:
storeimages.java servlet
public class storeimages extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String sav_dir=""; //this will be a folder inside
//directory
PrintWriter out =response.getWriter();
//if you want u can give this at run time
sav_dir="6022"; //in my case folder name is 6022
//you can alse set this at dynamic
int flag = 0;
//now set the path
//this is the path where my images are stored
//now u can see the code
String savepath="K:/imageupload"+File.separator +sav_dir;
File file = new File(savepath);
if(!file.exists()){
file.mkdir();
}
String filename="";
List<Part> fileParts = request.getParts().stream().
filter(part->"file".equals(part.getName())).collect(Collectors.
toList());
for(Part filePart: fileParts){
filename=Paths.get(filePart.getSubmittedFileName()).
getFileName().toString();
filePart.write(savepath+File.separator+filename);
flag=1;
}
if(flag==1){
out.println("success");
}
else{
out.println("try again");
}
//now save this and run the project
}
}
You only have to write multiple, because multiple is a boolean var and only defining it, it will be true to your tag. Example below:
<input type="file" name="file" id="file" multiple/>
This will let you choose multiple files at once. Good luck
This is how I did. It will dynamically add and remove the field (multiple files). Validates it and on validation calls the action method i.e the servlet and store in the DB.
** html/jsp **
.jsp file
<div class="recent-work-pic">
<form id="upload_form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input type="hidden" id="counter" value="1" >
Add
<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_0" class="upload_input"></div>
<div id="add_field_div"></div>
<button type="submit" class="btn btn-read">Submit</button>
</form>
<p>${message}</p>
</div>
jquery validation
<script>
$(document).ready(function(){
$('#add_fields').click( function(){
add_inputs()
});
$(document).on('click', '.remove_fields', function() {
$(this).closest('.record').remove();
});
function add_inputs(){
var counter = parseInt($('#counter').val());
var html = '<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_' + counter + '" class="upload_input">Remove</div>';
$('#add_field_div').append(html);
$('#counter').val( counter + 1 );
}
$('form#upload_form').on('submit', function(event) {
//Add validation rule for dynamically generated name fields
$('.upload_input').each(function() {
$(this).rules("add",
{
required: true,
messages: {
required: "File is required",
}
});
});
});
$("#upload_form").validate();
});
</script>
servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
PrintWriter writer = response.getWriter();
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("/resources/datenBank.properties"));
if (!ServletFileUpload.isMultipartContent(request)) {
writer.println("Fehler: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
String message = null;
InputStream inputStream = null;
Connection dbConnection = null;
String page = "";
try {
for (Part filePart : request.getParts()) {
System.out.println("filePart" + filePart.getName() + "-----" + filePart.getSize());
if (filePart != null && filePart.getSize() != 0) {
inputStream = filePart.getInputStream();
System.out.println("inputStream" + inputStream);
HttpSession session=request.getSession();
session.setAttribute("username",request.getRemoteUser());
Class.forName(properties.getProperty("driverClassName"));
dbConnection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
if (dbConnection != null) {
String sql = "INSERT INTO skl_lieferung (file_name, file_size, file_content,file_content_type, entry_time, user) values (?,?,?,?,?, ?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
if (inputStream != null) {
statement.setString(1, getFileName(filePart));
statement.setLong(2, filePart.getSize());
statement.setBlob(3, inputStream);
statement.setString(4, filePart.getContentType());
}
Calendar calendar = Calendar.getInstance();
java.sql.Date entryDate = new java.sql.Date(calendar.getTime().getTime());
statement.setDate(5, entryDate);
statement.setString(6, request.getRemoteUser());
//statement.setString(6, username);
int row = statement.executeUpdate();
if (row > 0) {
message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
message = "Fehler: Connection Problem";
}
} message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
page = "index.jsp";
System.out.println("cannot execute if condition");
message = "Das Upload-Feld darf nicht leer sein ";
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
return;
}
}
}catch (Exception exc) {
page = "index.jsp";
message = "Fehler: " + exc.getMessage();
exc.printStackTrace();
} finally {
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
page = "index.jsp";
request.setAttribute("message", message);
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
}
}
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
I hope people find it useful!!
To upload a single file you should use a single tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.
That is, use the below line multiple times:
<input type="file" name="dataFile" id="fileChooser" /><br><br>
Refer this link for details
I hope this helps.

How to get uploaded file to local folder in spring surf java webscript?

I am uploading a file. I want to get the file and save to my local system.To do this i am using spring surf webscripts in java. Can any one tell me how i can get my file .
This is my ftl file :
<form name="frmUpload" id="frmUpload"action="${url.context}/upload" enctype="multipart/form-data" method="get">
<input type="file" size="40" id="toBeUploaded" name="toBeUploaded" tabindex="2" onchange = "document.getElementById('frmUpload').submit()"required />
</form>
I am creating a backed java webscript to get this file. Here is my java code.
public class Upload extends DeclarativeWebScript{
protected ServiceRegistry serviceRegistry;
private static final long serialVersionUID = 1L;
private String fileName;
private String filePath;
private File toBeUploaded;
private String toBeUploadedFileName = "";
private String toBeUploadedContentType;
/** Multi-part form data, if provided */
private FormData formData;
/** Content read from the inputstream */
private Content content = null;
// upload settings
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
#Override
protected Map executeImpl(WebScriptRequest req,Status status) {
System.out.println("backed webscript called");
Boolean isMultipart = false;
String fileName = req.getParameter("toBeUploaded");
if(fileName == null){
System.out.println("File Name is null");
}else{
System.out.println("File Name is :" + fileName);
}
HttpServletRequest request = ServletUtil.getRequest();
String file = request.getParameter("toBeUploaded");
File file2 = new File(file);
String filePath = request.getSession().getServletContext().getRealPath("/");
File fileToCreate = new File(filePath, this.toBeUploadedFileName);
System.out.println("filepath "+filePath);
try {
FileUtils.copyFile(file2, fileToCreate);
//validateBundle(fileToCreate);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("filetocreate "+fileToCreate);
}
}
file name is comming properly but it is throwing FileNotFoundExeption. Here is stacktrace
java.io.FileNotFoundException: Source 'test.jar' does not exist
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:637)
at org.apache.commons.io.FileUtils.copyFile(FileUtils.java:607)
To get the uploaded form, you need to go via the FormData object. Your code will want to be something like:
// Get our multipart form
final ResourceBundle rb = getResources();
final FormData form = (FormData)req.parseContent();
if (form == null || !form.getIsMultiPart())
{
throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_BAD_FORM);
}
// Find the File Upload file, and process the contents
boolean processed = false;
for (FormData.FormField field : form.getFields())
{
if (field.getIsFile())
{
// Logic to process/save the file data here
processUpload(
field.getInputStream(),
field.getFilename());
processed = true;
break;
}
}
// Object if we didn't get a file
if (!processed)
{
throw new ResourceBundleWebScriptException(Status.STATUS_BAD_REQUEST, rb, ERROR_NO_FILE);
}
If you're sure of the field name of the upload, you can short circuit a few of those bits of logic

Categories

Resources