HTML5 拖放文件上传到 Java Servlet [英] HTML5 drag'n'drop file upload to Java Servlet

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

问题描述

我的问题说明了一切.我目前正在成功地使用 Uploadify(Flash + Ajax)到 Servlet(Commons Upload w/OWASP ESAPI 覆盖),但我想知道我将如何构建 HTML5 支持,或者更确切地说是支持 Flash 的 HTML5.

My question kind of says it all. I am currently using Uploadify (Flash + Ajax) to the Servlet (Commons Upload w/ OWASP ESAPI overlay) with success, but I was wondering how I would go about building in HTML5 support, or rather HTML5 with flash support.

我知道如何让 HTML5 DnD 工作,但我不太清楚 Java Servlet 连接和/或后端的机制.我搜索了很多地方,但找不到任何答案,因此非常感谢您的帮助.

I know how to get the HTML5 DnD working, but I can't quite figure out the mechanics of a Java Servlet connection and/or backend. I have searched lots of places, but I can't find any answers, so any help at all is appreciated.

推荐答案

我知道如何让 HTML5 DnD 工作,但我不太明白 Java Servlet 连接和/或后端的机制.

这与使用常规 <form enctype="multipart/form-data"> 时没有什么不同.您需要做的就是让 HTML5/JS 代码发送一个带有删除文件的 multipart/form-data 请求,与使用常规 <代码> 字段.我假设您只是不知道如何使用 HTML5/JS 实现这一点.

It's not different from when using a regular <form enctype="multipart/form-data">. All you need to do is to get that HTML5/JS code to send a multipart/form-data request with the dropped file, exactly the same kind of request as it would have been sent with a regular <input type="file"> field. I'll assume that you just can't figure out how to achieve exactly that with HTML5/JS.

您可以使用新的 HTML5 File API,XHR2 FormDataXMLHttpRequestUpload 用于此的 API.

You can utilize the new HTML5 File API, XHR2 FormData and XMLHttpRequestUpload APIs for this.

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

Here's a kickoff example of how your drop event handler should look like:

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 中可用,作为具有 file 字段名称的 FileItem 实例.

That's it. This example assumes that the servlet is mapped on a URL pattern of /uploadServlet. In this example, the file is then available in Apache Commons FileUpload the usual way as a FileItem instance with a field name of file.

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

For more advanced stuff like attaching event handlers for monitoring the progress and like, checkout the following blogs:

我使用以下 SSCCE 进行了一些尝试:

I've played somewhat around it with the following 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.0 HttpServletRequest#getPart() API:

and this UploadServlet utilizing the new Servlet 3.0 HttpServletRequest#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;
    }
}

另见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆