Clicky

when i try to upload two file and use  
out.println(item.getName()); it can display the two file name like : abc.gif and cde.gif

how do i display this two file name in jsp with two text input.

thanks


 <fieldset>
        <legend>Upload File</legend>
        <form action="uploadservlet" method="post" enctype="multipart/form-data">
            <label for="filename_1">File: </label>
            <input id="filename_1" type="file" name="filename_1" size="50"/><br/>
            <label for="filename_2">File: </label>
            <input id="filename_2" type="file" name="filename_2" size="50"/><br/>
            <br/>
            <input type="submit" value="Upload File"/>
        </form>
    </fieldset>

index.jsp

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Iterator;

public class FileUploadDemoServlet extends HttpServlet {
    private static final long serialVersionUID = -3208409086358916855L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         PrintWriter out = response.getWriter();
          response.setContentType("text/plain");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                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);
                        out.println(item.getName());

                        request.getSession().setAttribute("item", item);
                                        response.sendRedirect("cde.jsp");
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

FileUploadDemoServlet.java

asked 12/08/2011 09:45

aaronyeo22's gravatar image

aaronyeo22 ♦♦


18 Answers:
>>out.println(item.getName()); it can display the two file name like : abc.gif and cde.gif

Just pass the jsp a parameter called 'filenames' say. Concatenate the strings produced by the code i quoted into a comma-separated list
link

answered

CEHJ's gravatar image

CEHJ

changed little bit in servlet

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();

		int i=1;
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();
			i=i+1;

                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/uploads");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        File uploadedFile = new File(path + "/" + fileName);
                        out.println(item.getName());

                        request.getSession().setAttribute("item"+i, item.getName());
                                        response.sendRedirect("cde.jsp");
                        item.write(uploadedFile);
                    }
                }


JSP
*****

		String item1 = (String) request.getSession().setAttribute("item1");
		String item2 = (String) request.getSession().setAttribute("item2");

		<input id="filename_1" type="file" name="filename_1" size="50" value='<%=item1%>'/><br/>
            <input id="filename_2" type="file" name="filename_2" size="50" value='<%=item2%>'/><br/>
link

answered 2011-12-09 at 05:57:39

chaituu's gravatar image

chaituu

sorry you should initialize i as 0;
i=0;
link

answered 2011-12-09 at 06:02:53

chaituu's gravatar image

chaituu

String item1 = (String) request.getSession().getAttribute("item1");
            String item2 = (String) request.getSession().getAttribute("item2");

link

answered 2011-12-09 at 06:05:49

chaituu's gravatar image

chaituu

>>String item1 = (String) request.getSession().getAttribute("item1");

How will you know how many items there are?
link

answered 2011-12-09 at 06:07:09

CEHJ's gravatar image

CEHJ

as he is expecting two .gif files.so we can hardcoded with item1 amd item2 etc..;but that is not the generic way.
link

answered 2011-12-09 at 06:14:54

chaituu's gravatar image

chaituu

he is having only textboxes so we have hardcodes.if he is having multiple text boxes then it is better to follow another approach.
link

answered 2011-12-09 at 06:18:54

chaituu's gravatar image

chaituu

2 textboxes
link

answered 2011-12-09 at 06:20:33

chaituu's gravatar image

chaituu

>>he is having only textboxes so we have hardcodes.

That's true. Probably better to do it generically though imo
link

answered 2011-12-09 at 06:21:23

CEHJ's gravatar image

CEHJ

thanks
link

answered 2011-12-09 at 06:22:00

aaronyeo22's gravatar image

aaronyeo22

First of all the above code will not execute for both the files as response.sendRedirect("cde.jsp"); is used inside the while loop,so the code will redirect before executing for both files.

To send the file names to jsp,you can simply add the file names in a list and set the list in session as it is done :

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List items = upload.parseRequest(request);
      Iterator iterator = items.iterator();
      List<String> filenames = new ArrayList<String>();
      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);
          filenames.add(fileName);                              
          item.write(uploadedFile);
        }
    }
    request.getSession().setAttribute("item", filenames);
    response.sendRedirect("cde.jsp");  
    } catch (FileUploadException e) {
              e.printStackTrace();
    } catch (Exception e) {
              e.printStackTrace();
    }
}

**********JSP*********
<%
java.util.List<String> filenames = (java.util.List<String>)request.getSession().getAttribute("item");
for(String filename: filenames) {
%>
      <input id="filename_1" type="text"" name="filename_1" size="50" value='<%=filename%>'/><br/>
<%
}
%>

Hope this helps :)
link

answered 2011-12-10 at 03:30:37

sunu340's gravatar image

sunu340

yes you are correct.there are so many approaches to send the list to jsp.this is one of them.even putting filenames to session you can print the filenames using request scope.
link

answered 2011-12-10 at 04:05:39

chaituu's gravatar image

chaituu

sunu340 can help me
link

answered 2011-12-10 at 04:22:09

aaronyeo22's gravatar image

aaronyeo22

really sorry . chaituu only can upload one file. but yours one is two files. but after i submit that becomes 4 text input. i just want two. thanks
link

answered 2011-12-10 at 05:26:31

aaronyeo22's gravatar image

aaronyeo22

fix already. thanks sunu340
link

answered 2011-12-10 at 05:28:00

aaronyeo22's gravatar image

aaronyeo22

chaituu: your solution only able to upload one file. sorry
link

answered 2011-12-10 at 05:31:25

aaronyeo22's gravatar image

aaronyeo22

>>chaituu: your solution only able to upload one file. sorry

Worries about the number of files it allows just show, as i mentioned earlier, that the solution should be generic - so it doesn't matter how many there are.
link

answered 2011-12-10 at 06:04:21

CEHJ's gravatar image

CEHJ

link

answered 2011-12-10 at 08:58:24

chaituu's gravatar image

chaituu

Your answer
[hide preview]

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Tags:

×1

Asked: 12/08/2011 09:45

Seen: 378 times

Last updated: 12/09/2011 07:30