0

I have this code in my jsp side:

<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>Select File : </td>
                <td><input  name="file" type="file"/> </td>
            </tr>
            <tr>
                <td>Enter Filename : </td>
                <td><input type="text" name="photoname" size="20"/> </td>
            </tr>
        </table>
        <p/>
        <input type="submit" value="Upload File"/>
    </form>
 </body>

This uploads a single file.

And in the servlet, I have the code:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            Part p1 = request.getPart("file");
            InputStream is = p1.getInputStream();


            Part p2 = request.getPart("photoname");
            Scanner s = new Scanner(p2.getInputStream());
            String filename = s.nextLine();   



            // get filename to use on the server
            String outputfile = "C:\\Documents and Settings\\Sherman\\Desktop\\ImoveiSP\\ImoveiSP\\DB_Scripts" + filename + ".jpg";
            //outputfile = outputfile + ".jpg";
            //System.out.println("out  = " + outputfile);
            FileOutputStream os = new FileOutputStream(outputfile);

            // write bytes taken from uploaded file to target file
            int ch = is.read();
            while (ch != -1) {
                os.write(ch);
                ch = is.read();
            }
            os.close();
            out.println("<h3>File uploaded successfully! </h3>");


            File file = new File("C:\\Documents and Settings\\Sherman\\Desktop\\ImoveiSP\\ImoveiSP\\DB_Scripts" + filename + ".jpg");
            uploadAmazon(file, "ibagem", "");

        } catch (Exception ex) {
            out.println("Exception -->" + ex.getMessage());
        } finally {
            out.close();
        }
    }

This servlet takes the file uploaded and saves it to the disk.

I have two question about this codes:

  1. In jsp side, how can I force the user to send only .jpg or .mpg files?
  2. If I put more then one input to upload in the jsp side, how I receive all in servlet?
Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
Shermano
  • 1,100
  • 8
  • 31
  • possible duplicate of [How to upload files in JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824) – BalusC Nov 08 '11 at 00:11

1 Answers1

1

I'd recommend using Commons FileUpload for handling all of this; it makes things much easier. See the user guide for details.

Handling multiple files is the same as handling a single file.

I'd recommend moving that absolute pathname into a configuration parameter, btw.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302