Java 使用dropzone发送多部分加密数据

Java 使用dropzone发送多部分加密数据,java,jsp,dropzone.js,Java,Jsp,Dropzone.js,这是我的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> <h

这是我的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>

$(文档).ready(函数()
{
var myDropzone=newdropzone(“div#my awesome Dropzone”{url:'UploadServlet'});
Dropzone.autoDiscover=false;
myDropzone.on(“addedfile”,函数(文件){
//创建删除按钮
var removeButton=Dropzone.createElement(“删除文件”);
//将Dropzone实例捕获为闭包。
var_this=这个;
//收听单击事件
removeButton.addEventListener(“单击”),函数(e){
//确保单击按钮不会提交表单:
e、 预防默认值();
e、 停止传播();
//删除文件预览。
_此.removeFile(文件);
//如果还要删除服务器上的文件,
//您可以在这里执行AJAX请求。
});
//将按钮添加到文件预览元素。
file.previewElement.appendChild(removeButton);
});
$(“#按钮”)。单击(函数(){
var source=$(“#我最棒的dropzone”).attr(“src”);
警报(来源);
});
});
在此处插入标题
唯一ID:
姓名:
年龄:
地址:
电话号码
这是我的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);
        }

    }
}
/*
*要更改此模板,请选择工具|模板
*然后在编辑器中打开模板。
*/
包装投放区;
导入java.io.File;
导入java.io.InputStream;
导入java.sql.Connection;
导入java.sql.DriverManager;
导入javax.servlet.*;
导入javax.servlet.http.*;
导入java.io.IOException;
导入java.sql.Connection;
导入java.sql.DriverManager;
导入java.sql.PreparedStatement;
导入java.sql.SQLException;
导入java.util.List;
导入javax.servlet.ServletException;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入javax.swing.text.html.HTMLDocument.Iterator;
导入org.apache.commons.fileupload.FileItem;
导入org.apache.commons.fileupload.FileItemFactory;
导入org.apache.commons.fileupload.FileUploadException;
导入org.apache.commons.fileupload.disk.DiskFileItemFactory;
导入org.apache.commons.fileupload.servlet.ServletFileUpload;
导入org.apache.commons.io.FilenameUtils;
导入com.oreilly.servlet.multipart.MultipartParser;
导入com.oreilly.servlet.multipart.Part;
导入com.oreilly.servlet.multipart.FilePart;
公共类UploadServlet扩展了HttpServlet{
私有字符串文件保存路径;
私有静态最终字符串上载\u DIRECTORY=“UPLOAD”;
公共void init(){
fileSavePath=getServletContext().getRealPath(“/”)+File.separator+UPLOAD_目录;/*将上传的文件保存到web应用程序中的“UPLOAD”目录*/
如果(!(新文件(fileSavePath)).exists()){
(新文件(fileSavePath)).mkdir();//如果目录不存在,则创建该目录
}
}
@凌驾
public void doPost(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,java.io.IOException{
连接con=null;
清单项目;
试一试{
items=new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
用于(文件项:项){
if(item.isFormField()){
//处理常规表单字段(输入type=“text | radio | checkbox | etc”,选择等)。
字符串fieldname=item.getFieldName();
String fieldvalue=item.getString();
//…(在这里做你的工作)
}否则{
//处理表单文件字段(输入类型=“文件”)。
字符串fieldname=item.getFieldName();
字符串filename=FilenameUtils.getName(item.getName());
InputStream filecontent=item.getInputStream();
//…(在这里做你的工作)
}
}
}捕获(文件上载异常e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
/*
字符串uid=request.getParameter(“唯一”);
字符串fullname=request.getParameter(“fullname”);
System.out.println(全名);
字符串年龄=request.getParameter(“年龄”);
字符串地址=request.getParameter(“地址”);
字符串phonenumber=request.getParameter(“phonenumber”)*/
字符串路径=null;
字符串消息=null;
字符串resp=“”;
int i=1;
resp+=“
这里是有关上载文件的信息。
”; 试一试{ registerDriver(新的com.mysql.jdbc.Driver()); con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/dropzone“,”根“,”根“); String sql=“插入详细信息(u_id、姓名、年龄、地址、电话号码、路径)值(?,,,,,?,?)”; PreparedStatement=con.prepareStatement(sql); //##########################################################?// MultipartParser parser=新的MultipartParser(请求,1024*1024*1024);/*文件大小限制为1GB*/ 部分(u部分),; 而((_part=parser.readNextPart())!=null){ 如果(_part.isFile()){ FilePart fPart=(FilePart)\u part;//获取有关该文件的一些信息 字符串名称=fPart.getFileName(); if(name!=null){ long fileSize=fPart.writeTo(新文件(fileSavePath)); 响应
<form action="UploadServlet" id="mydropzone" class="dropzone" method="post" enctype="multipart/form-data" >
<div id="dropzonePreview"></div>
<input type="submit" id="sbmtbtn" value="Submit data and files!" />
 <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>