如何使用java上传文件夹 [英] how to upload a folder using java

查看:71
本文介绍了如何使用java上传文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何上传文件夹以便在项目webroot中创建文件夹 - > gallery->< folder name =>并且路径将存储在数据库中,例如gallery \< folder_name> ;.



我使用了以下代码,但它将从文件夹中获取单个图像进行上传。但我想一次上传总文件夹。怎么做?以下是我试过的代码。



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: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>

< br $>




Dao类:






Dao class:

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

推荐答案

ExtractFileSubDirectories.java

-------------------------------





ExtractFileSubDirectories.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页面:



Fileupload.jsp









jsp page:

Fileupload.jsp



<![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>
<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>


使用的控件是文件的输入。这意味着这不适用于完整的文件夹。查看uploadify,这可能是解决您问题的好方法。

http://www.uploadify.com/ [ ^ ]



祝你好运!
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!


这篇关于如何使用java上传文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆