Click here to Skip to main content
15,889,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to upload a folder so that folder will be created in project webroot-> gallery-><folder name=""> and the path will be stored in database like gallery\<folder_name>.

i have used the follwing code but it will take single image from the folder for uploading. But i want upload total folder at a time. how to do? follwing is my code what i have tried.

HTML
 <html:form  action="/addmovie.do" method="post" enctype="multipart/form-data" >
 <input type="file" name="file" id="label"/>
<html:submit value="Insert" styleId="submit"></html:submit>



Dao class:

Java
public class AddMovieDao {
	public static AddMovieFormBean insert(AddMovieFormBean bean) {
		try {
			PathReturn path = new PathReturn();
			String realpath = path.getPath();
			System.out.println("path is" + realpath);
			FormFile file = bean.getFile();
			String filePath = realpath + "allimages";
			String dbpath = "D:\\allimages\\" + file.getFileName();
			File folder = new File(filePath);
			if (!folder.exists()) {
				folder.mkdir();
			}
			String fileName = file.getFileName();
			if (!("").equals(fileName)) {
				System.out.println("Server path:" + filePath);
				File newFile = new File(filePath, fileName);
				if (!newFile.exists()) {
					FileOutputStream fos = new FileOutputStream(newFile);
					fos.write(file.getFileData());
					fos.flush();
					fos.close();
				}
			}

			Connection con = (Connection) new  
                           DB2Connection().getDatabaseConnection();
			String sql = "insert into movies(movie_image) values(?) ";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setString(1, dbpath);
			int ok = ps.executeUpdate();
			}
		} catch (SQLException e) {

			e.printStackTrace();

		} catch (NullPointerException nl) {
			nl.printStackTrace();
		}
		catch (Exception ex) {

			ex.printStackTrace();
		}
		return bean;
	}
}


but it uploads single image. how to upload entire folder at a time. please help me.

Thanks in Advance
Posted

ExtractFileSubDirectories.java
-------------------------------


Java
public class ExtractFileSubDirectories {
       
         public static void unzip(String strZipFile) {
               
                try
                {
                     
                		System.out.println("In java Class:");
                        File fSourceZip = new File(strZipFile);
                        String zipPath = strZipFile.substring(0, strZipFile.length()-4);
                        File temp = new File(zipPath);
                        temp.mkdir();
                        System.out.println(zipPath + " created");
                       
                       
                        ZipFile zipFile = new ZipFile(fSourceZip);
                        Enumeration e = zipFile.entries();
                       
                        while(e.hasMoreElements())
                        {
                                ZipEntry entry = (ZipEntry)e.nextElement();
                                File destinationFilePath = new File(zipPath,entry.getName());
                                destinationFilePath.getParentFile().mkdirs();
                                if(entry.isDirectory())
                                {
                                        continue;
                                }
                                else
                                {
                                        System.out.println("Extracting " + destinationFilePath);
                                 
                                        BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                                                                                                                       
                                        int b;
                                        byte buffer[] = new byte[1024];
                                         FileOutputStream fos = new FileOutputStream(destinationFilePath);
                                        BufferedOutputStream bos = new BufferedOutputStream(fos,
                                                                        1024);
 
                                        while ((b = bis.read(buffer, 0, 1024)) != -1) {
                                                        bos.write(buffer, 0, b);
                                        }
                                     
                                        bos.flush();
                                        bos.close();
                                        fos.close();
                                  
                                        bis.close();
                                       
                                }
                        }
                        zipFile.close();
                        System.out.println(fSourceZip.delete());   
                }
                catch(IOException ioe)
                {
                	ioe.printStackTrace();
                        //System.err.println("IOError :" + ioe.getMessage());
                }
                catch(Exception e){
                	e.printStackTrace();
                }
               
        }
}


jsp page:

Fileupload.jsp



Java
<![CDATA[<%
 	 String OUTPUT_FOLDER = getServletContext().getRealPath("/Upload");
      String saveFile = "";
      String contentType = request.getContentType();
      if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
            DataInputStream in = new DataInputStream(request.getInputStream());
            int formDataLength = request.getContentLength();
            
            byte dataBytes[] = new byte[formDataLength];
            int byteRead = 0;
            int totalBytesRead = 0;
            while (totalBytesRead < formDataLength) {
                  byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                  totalBytesRead += byteRead;
            }
            String file = new String(dataBytes);
            saveFile = file.substring(file.indexOf("filename=\"") + 10);
            saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
            saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
            int lastIndex = contentType.lastIndexOf("=");
            String boundary = contentType.substring(lastIndex + 1, contentType.length());
            int pos;
            pos = file.indexOf("filename=\"");
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            int boundaryLocation = file.indexOf(boundary, pos) - 4;
            int startPos = ((file.substring(0, pos)).getBytes()).length;
            int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
          
          	saveFile = OUTPUT_FOLDER +"\\"+ saveFile;
          	//System.out.println(saveFile);
            File ff = new File(saveFile);
            FileOutputStream fileOut = new FileOutputStream(ff);
            fileOut.write(dataBytes, startPos, (endPos - startPos));
            fileOut.flush();
            fileOut.close();
           
%>]]><br>
<table border="2">
      <tr>
            <td>You have successfully upload the file by the name of:
            <%
            	out.println(saveFile);
                         com.winnova.struts.action.ExtractFileSubDirectories.unzip(saveFile);
                              }
                              else{
                              System.out.println("------------------"+contentType);
                              }
            %>
            </td>
      </tr>
</table>

</br>


HTML
<HTML>
<HEAD>
<TITLE>Display file upload form to the user</TITLE>
</HEAD>
<BODY>
<FORM ENCTYPE="multipart/form-data" ACTION="fileUpload.jsp" METHOD=POST>
<br>
<br>
<br>

<table border="1" bgcolor="#ccFDDEE">
      <tr>
            <td colspan="2" align="center">UPLOAD THE FILE</td>
      </tr>
      <tr>
            <td>File Name:</td>
            <td><INPUT NAME="files" TYPE="text"></td>
      </tr>
       <tr>
            <td>Choose the file To Upload:</td>
            <td><INPUT NAME="file" TYPE="file"></td>
      </tr>
     
      <tr>
            <td colspan="2" align="center"><input type="submit" value="Send File"></td>
      </tr>
     </table>
          
            </FORM>
</BODY>
</HTML>

</br></br></br>
 
Share this answer
 
Comments
Member 12600941 23-Jun-16 17:27pm    
The above code helped me but I am stuck at the point of opening that folder's html page on click of a link.
The folder was uploaded at location
C:\Users\AyushiTaneja\Documents\NetBeansProjects\e3store\build\web\Upload/physics/
with name Material Design Lite MDL because of getRealPath().
when i gave the same location in href it is trying to open
localhost:8084/C:\Users\AyushiTaneja\Documents\NetBeansProjects\e3store\build\web\Upload/physics/Material Design Lite MDL /Material Design Lite MDL /
which does not exist.

I am at the end of a project and am stuck with this. Kindly guide me in this , if I can change the upload location say in the same location where the code exists then it would solve all the problrem.

Thank you.
Member 12704134 26-Aug-16 0:15am    
I used this code , but it's not work for the FOLDER/DIRECTORY uploading case. Please help me to do this.
The control used is an input for a file. meaning this will not be suitable for complete folders. Check out uploadify, that could be a nice solution to your problem.
http://www.uploadify.com/[^]

Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900