Sending multipart encryption data using dropzone

Here is my index.html:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <script src="extra/js/jquery-1.10.2.min.js"></script>
    <script src="extra/downloads/dropzone.js"></script>
    <script>
        $(document).ready(function()
        {
            var myDropzone = new Dropzone("div#my-awesome-dropzone", {url:'UploadServlet'});
            Dropzone.autoDiscover = false;

            myDropzone.on("addedfile", function(file) {

            // Create the remove button
            var removeButton = Dropzone.createElement("<button>Remove file</button>");


            // Capture the Dropzone instance as closure.
            var _this = this;

            // Listen to the click event
            removeButton.addEventListener("click", function(e) {
              // Make sure the button click doesn't submit the form:
              e.preventDefault();
              e.stopPropagation();

              // Remove the file preview.
              _this.removeFile(file);
              // If you want to the delete the file on the server as well,
              // you can do the AJAX request here.
            });

            // Add the button to the file preview element.
            file.previewElement.appendChild(removeButton);
          });
            $("#button").click(function(){
                var source = $("#my-awesome-dropzone").attr("src");
                alert(source);
            });
        });
    </script>

    <link rel="stylesheet" href="extra/downloads/css/dropzone.css" type="text/css">
    <title>Insert title here</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data" >
    <table id="table">
        <tr>
            <td> Unique ID : </td> 
            <td><input type="text" id="unique" name="unique" maxlength="6" required></input></td>
        </tr>
        <tr>
            <td> Name : </td> 
            <td><input type="text" id="fullname" name="fullname" maxlength="255" required></input></td>
        </tr>
        <tr>
            <td> Age : </td>
            <td><input type="text" id="age" name="age" maxlength="255" required></input></td>
        </tr>
        <tr>
            <td> Address : </td>
            <td><input type="text" id="address" name="address" maxlength="255" required></input></td>
        </tr>
        <tr>
            <td> Phone_number </td>
            <td><input type="text" id="phonenumber" name="phonenumber" maxlength="10" required></input></td>
        </tr>
    </table>
    <div id="my-awesome-dropzone" class="dropzone"></div>
    <div>
        <input type="submit" value="Submit data and files!"></input>
    </div>
</form>
</body>
</html>

And this my servlet:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dropzone;

import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTMLDocument.Iterator;

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;
import org.apache.commons.io.FilenameUtils;

import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;

public class UploadServlet extends HttpServlet {

    private String fileSavePath;
    private static final String UPLOAD_DIRECTORY = "upload";

    public void init() {
        fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
        if (!(new File(fileSavePath)).exists()) {
            (new File(fileSavePath)).mkdir();    // creates the directory if it does not exist        
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
        Connection con = null;

        List<FileItem> items;
        try {
            items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String fieldvalue = item.getString();
                    // ... (do your job here)
                } else {
                    // Process form file field (input type="file").
                    String fieldname = item.getFieldName();
                    String filename = FilenameUtils.getName(item.getName());
                    InputStream filecontent = item.getInputStream();
                    // ... (do your job here)
                }
            }
        } catch (FileUploadException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        /*
        String uid = request.getParameter("unique");
        String fullname = request.getParameter("fullname");
        System.out.println(fullname);
        String age = request.getParameter("age");
        String address = request.getParameter("address");
        String phonenumber = request.getParameter("phonenumber");*/
        String path = null;
        String message = null;
        String resp = "";
        int i = 1;
        resp += "<br>Here is information about uploaded files.<br>";

        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dropzone", "root", "root");

            String sql = "INSERT INTO details(u_id,name,age,address,phonenumber,path) values(?,?,?,?,?,?)";
            PreparedStatement statement = con.prepareStatement(sql);

            //##########################################################?//

            MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024);  /* file limit size of 1GB*/
            Part _part;
            while ((_part = parser.readNextPart()) != null) {
                if (_part.isFile()) {
                    FilePart fPart = (FilePart) _part;  // get some info about the file
                    String name = fPart.getFileName();
                    if (name != null) {
                        long fileSize = fPart.writeTo(new File(fileSavePath));
                        resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
                    } else {
                        resp = "<br>The user did not upload a file for this part.";
                    }
                }
            }// end while 

            //##################################################################//
            statement.setString(1,"uid");
            statement.setString(2,"fullname");
            statement.setString(3,"age");
            statement.setString(4,"address");
            statement.setString(5,"phonenumber");
            statement.setString(6,"path");
            int row = statement.executeUpdate();
            if(row>0){
                message = "Contact saved";
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message = "ERROR: " +e.getMessage();

        }
        finally
        {
            if(con !=null)
            {
                try{
                    con.close();

                }
                catch(SQLException ex)
                {
                    ex.printStackTrace();
                }
            }
            System.out.println(message);
            request.setAttribute("Message",message);
            getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
        }

    }
}

Here is screenshot of the error:

I want to use the dropzone for uploading images.But if I use multipart/form-data for the form, the fields except the images give null values. I tried using the simple getParameter method. But it doesnt seem to work. Also I tried using Lists but it gives an error. Anyone tried dropzone with jsp?? Help

Answers


This is happening because you are not treating the whole form as dropzone but you are treating only the #my-awesome-dropzone div as dropzone .That won't work if you want to submit whole form with the files on one click.

1)In the form tag add an id say id="mydropzone" and class class="dropzone"

<form action="UploadServlet" id="mydropzone" class="dropzone" method="post" enctype="multipart/form-data" >

2)Remove the div from your code which has the id id="my-awesome-dropzone".Then Add a new div to show the files uploaded in drag and drop

<div id="dropzonePreview"></div>

3)add an id to your submit button

<input type="submit" id="sbmtbtn" value="Submit data and files!" />

4)now add this script

 <script>
Dropzone.options.mydropzone = {
// url does not has to be written if we have wrote action in the form tag but i have mentioned here just for convenience sake 
          addRemoveLinks: true,
          autoProcessQueue: false, // this is important as you dont want form to be submitted unless you have clicked the submit button
          autoDiscover: false,
          paramName: 'pic', // this is similar to giving name to the input type file like <input type="file" name="pic" />
          previewsContainer: '#dropzonePreview', // we specify on which div id we must show the files
          clickable: false, // this tells that the dropzone will not be clickable . we have to do it because v dont want the whole form to be clickable 
          accept: function(file, done) {
            console.log("uploaded");
            done();
          },
         error: function(file, msg){
            alert(msg);
          },
          init: function() {

              var myDropzone = this;
            //now we will submit the form when the button is clicked
                document.getElementById("sbmtbtn").onclick = function(e) {
               e.preventDefault(); //this will prevent the default behaviour of submit button because we want dropzone to submit the form
               myDropzone.processQueue(); // this will submit your form to the specified action which directs to your jsp upload code
              // after this, your whole form will get submitted with all the inputs + your files and the jsp code will remain as usual 
        //REMEMBER you DON'T have to call ajax or anything by yourself to submit the inputs, dropzone will take care of that
            };

          } // init end

        };
</script>

NOTE :

  1. YOU DO NOT have to write any extra code to make the form submit .
  2. After writing the above code just follow your normal flow to upload file in jsp like writing the xml and writing the servlet class and fetch all the inputs and files there.
  3. Remember dropzone uses ajax to upload so the form will not be refreshed when you click submit.
  4. You cannot click on the form to upload files now you have to just drag the files in the form.

Need Your Help

How can I run git push/pull commands with SSH verbose mode?

git ssh

If I run "git push" with the GIT_TRACE=2 environment variable, I get the following:

symfony2 many to many entity form

forms authentication symfony many-to-many

I have two entites User Role. Both are used in Symfony2 for authentication. The authentication process needs to have method 'getRoles' in class User which returns array.