如何在拖放html5中传递id

时间:2012-03-29 13:47:34

标签: java html5 jsp servlets

的index.jsp

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>HTML5 drag'n'drop file upload with Servlet</title>
        <script>
            window.onload = function() {
                var dropbox = document.getElementById("dropbox");
                dropbox.addEventListener("dragenter", noop, false);
                dropbox.addEventListener("dragexit", noop, false);
                dropbox.addEventListener("dragover", noop, false);
                dropbox.addEventListener("drop", dropUpload, false);
            }

            function noop(event) {
                event.stopPropagation();
                event.preventDefault();
            }

            function dropUpload(event) {
                noop(event);
                var files = event.dataTransfer.files;

                for (var i = 0; i < files.length; i++) {
                    upload(files[i]);
                }
            }

            function upload(file) {
                document.getElementById("status").innerHTML = "Uploading " + file.name;

                var formData = new FormData();
                formData.append("file", file);

                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener("progress", uploadProgress, false);
                xhr.addEventListener("load", uploadComplete, false);
                xhr.open("POST", "uploadServlet", false); // If async=false, then you'll miss progress bar support.
                xhr.send(formData);
            }

            function uploadProgress(event) {
                // Note: doesn't work with async=false.
                var progress = Math.round(event.loaded / event.total * 100);
                document.getElementById("status").innerHTML = "Progress " + progress + "%";
            }

            function uploadComplete(event) {
                document.getElementById("status").innerHTML = event.target.responseText;
            }
        </script>
        <style>
            #dropbox {
                width: 300px;
                height: 200px;
                border: 1px solid gray;
                border-radius: 5px;
                padding: 5px;
                color: gray;
            }
        </style>
    </head>
    <body>
        <div id="dropbox">Drag and drop a file here...</div>
        <div id="status"></div>
    </body>
</html>

uploadServlet.java

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

package officer;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class uploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            // Apache Commons-Fileupload library classes
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu  = new ServletFileUpload(factory);

            if (! ServletFileUpload.isMultipartContent(request)) {
                out.println("sorry. No file uploaded");
                return;
            }
            else
            {
            // parse request
            List items = sfu.parseRequest(request);

            FileItem file = (FileItem) items.get(0);
            String type=file.getContentType();
            float size=file.getSize()/1024;
            if((type.equals("image/jpeg"))&& ((size <201)&&(size>10)))
            {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "epolicia", "admin");
            con.setAutoCommit(false);
            PreparedStatement ps = con.prepareStatement("insert into image(image) values(?)");
            ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize());
            ps.executeUpdate();
            con.commit();
            con.close();
            out.println("Proto Added Successfully. <p> <a href='ListPhotoServlet'>List Photos </a>");
            }
            else
            {
             out.print("Invalid Image Selected !!");
            }
            }
        }
        catch(Exception ex) {
            out.println( "Error --> " + ex.getMessage());
        }
    }
}

上面的代码只是简单地将图像插入数据库。但是,我想在userid的基础上插入图像。然后,我应该在我的代码中改变什么。将图像放入框中时,需要帮助才能传递userid。在此先感谢!!

1 个答案:

答案 0 :(得分:2)

我在Chrome浏览器中对此进行了测试。 在你的脚本中;

formData.append("file", file);
// if userid is in your script
fd.append("userid", userid); 
// or if userid is at server, then send it to browser first
// fd.append("userid", <%=userid%>);

在UploadServlet中;

Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField()) {
        String userid = item.getString();
    else //its the file
 ...