使用jsp& amp;上传多个文件小服务程序

时间:2013-11-25 01:06:47

标签: java jsp servlets file-upload multiple-files

我目前正在开发一个动态Web应用程序,我希望用户能够一次上传多个文件以供应用程序使用。我不知道用户可以一次上传多少文件;它可能是2或它可能100多个文件。我是JSP动态Web应用程序的新手,我已经开始使用单个上传文件,但我不确定从哪里开始。我看过几个搜索的例子但是我找不到我想要的东西。这就是我到目前为止所做的:

的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文件:

<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
    <p><input type="file" name="dataFile" id="fileChooser" />&nbsp;
    <input type="submit" value="Upload" multiple="multiple" /></p>
</form>

我正在寻找一种方法来上传多个文件,而不只是一个文件,并在列表中显示。

7 个答案:

答案 0 :(得分:3)

检查 FileUPload Using Servlet 3.0

它有一个使用Servlet3.0上传单个文件的工作代码正如您所看到的,现在代码已经大大简化了。并且不依赖于apache库。

只需使用以下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="multiple"/>
<br>
<input type="submit" value="Upload"/>
</form>
</body>
</html>

此处仅更改是我已将multiple="multiple"属性用于输入类型File

答案 1 :(得分:1)

噢......乍一看,看起来像是一个简单的错误。 multiple是文件输入的属性,而不是提交按钮的属性。

答案 2 :(得分:1)

我使用jsp / servlet上传了多个文件。 以下是我使用的代码。

<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
另一方面服务器端

。使用以下代码。

    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();
                } 
            }   
    }

}

答案 3 :(得分:0)

images.jsp

  选择文件:

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

答案 4 :(得分:0)

你只需要编写 multiple ,因为multiple是一个布尔变量而且只定义它,它对你的标记是真的。示例如下:

<input type="file" name="file" id="file" multiple/> 

这将允许您一次选择多个文件。祝你好运

答案 5 :(得分:0)

这就是我的做法。它将动态添加和删除字段(多个文件)。对其进行验证,并在验证时调用操作方法,即servlet并存储在数据库中。 ** html / jsp ** .jsp文件

%F{1}

jquery验证

%F{#ff0000}

servlet

<div class="recent-work-pic">
<form id="upload_form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input type="hidden" id="counter" value="1" >
<a href="javascript:void(0);" class="remove_fields"  id="add_fields">Add</a>
<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>

我希望人们觉得它有用!!

答案 6 :(得分:-1)

要上传单个文件,您应该使用属性类型=“file”的单个标记。要允许多个文件上载,请包含多个具有不同name属性值的输入标记。浏览器将“浏览”按钮与每个按钮相关联。

即,多次使用以下行:

<input type="file" name="dataFile" id="fileChooser" /><br><br>

Refer this link for details

我希望这会有所帮助。