【问题标题】:Sending multipart encryption data using dropzone使用 dropzone 发送多部分加密数据
【发布时间】:2014-03-11 06:45:49
【问题描述】:

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

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

    }
}

这是错误的截图:

我想使用dropzone来上传图片。但是如果我使用multipart/form-data作为表单,除了图片之外的字段会给出空值。我尝试使用简单的 getParameter 方法。但它似乎不起作用。我也尝试使用列表,但它给出了一个错误。有人用jsp试过dropzone吗??帮助

【问题讨论】:

  • 需要更多解释..
  • @Rembo 我编辑了问题。
  • 而不是 img,请复制完整的错误消息并添加到您的问题中。这将有助于解决问题。

标签: java jsp dropzone.js


【解决方案1】:

发生这种情况是因为您没有将整个表单视为 dropzone 而是仅将 #my-awesome-dropzone div 视为 dropzone 。如果您想一键提交包含文件的整个表单,那将不起作用。

1)在表单标签中添加一个id,比如id="mydropzone"和类class="dropzone"

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

2)从你的代码中删除id为id="my-awesome-dropzone"的div。然后添加一个新的div来显示拖放上传的文件

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

3) 为您的提交按钮添加一个 id

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

4)现在添加这个脚本

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

注意

  1. 您不必编写任何额外的代码来提交表单。
  2. 写完以上代码后,按照正常流程上传即可 在 jsp 中编写文件,例如编写 xml 和编写 servlet 类并获取那里的所有输入和文件。
  3. 记住 dropzone 使用 ajax 上传,所以表单不会 点击提交时刷新。
  4. 您现在无法单击表单上传文件,您必须 拖动表单中的文件。

【讨论】:

  • 如果我想在提交表单时更新文件怎么办?所以我的 servlet 可以使用 getParts() 方法捕获它们然后保存它们?我不想使用 ajax,因为文件会在我提交表单之前上传。我希望所有输入和文件立即发送到我的 servlet 以便它可以处理它们?
猜你喜欢
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 2016-09-09
  • 2014-03-23
  • 2015-06-23
相关资源
最近更新 更多