HTML5拖放文件上载到Java Servlet

HTML5 drag and drop file upload to Java Servlet(HTML5拖放文件上载到Java Servlet)

本文介绍了HTML5拖放文件上载到Java Servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用Uploadify(Flash+AJAX)成功地将Servlet(Commons Upload With OWASP ESAPI Overlay)连接到Servlet,但我想知道如何构建HTML5支持,或者更确切地说,是支持Flash的HTML5。

我知道如何使HTML5拖放工作,但我不太清楚Java Servlet连接和/或后端的机制。

推荐答案

我知道如何使HTML5 DND正常工作,但我不太清楚Java Servlet连接和/或后端的机制。

它与使用常规<form enctype="multipart/form-data">时没有什么不同。您所需要做的就是让HTML5/JS代码发送一个multipart/form-data请求,该请求与使用常规<input type="file">字段发送的请求类型完全相同。我假设您无法通过HTML5/JS准确地实现这一点。

您可以使用新的HTML5File接口、XHR2FormDataXMLHttpRequestUpload接口。

下面是drop事件处理程序的启动示例:

function dropUpload(event) {
    event.stopPropagation();
    event.preventDefault();

    var formData = new FormData();
    formData.append("file", event.dataTransfer.files[0]);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "uploadServlet");
    xhr.send(formData);
}

就是这样。此示例假设Servlet映射到/uploadServlet的URL模式上。在本例中,该文件随后可在Apache Commons FileUpload中以通常方式作为FileItem实例,字段名为file


有关更高级的内容,如附加用于监视进度的事件处理程序等,请查看以下博客:

  • HTML5 Drag and Drop Upload and File API Tutorial
  • HTML5 File Upload With Progress

我使用以下SSCCE解决了这个问题:

<!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", true); // 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使用新的Servlet 3.0HttpServletRequest#getPart()API:

@MultipartConfig
@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part file = request.getPart("file");
        String filename = getFilename(file);
        InputStream filecontent = file.getInputStream();
        // ... Do your file saving job here.

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("File " + filename + " successfully uploaded");
    }

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace(""", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

另请参阅:

  • How to upload files to server using JSP/Servlet?

这篇关于HTML5拖放文件上载到Java Servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:HTML5拖放文件上载到Java Servlet

基础教程推荐