小编典典

HTML5文件上传到Java Servlet

html

我的问题有点说明了一切。我目前正在成功地将Uploadify(Flash + Ajax)用于Servlet(带有OWASP
ESAPI覆盖的公共上传),但是我想知道如何构建HTML5支持,或者说具有Flash支持的HTML5。

我知道如何使HTML5 DnD正常工作,但是我不太了解Java
Servlet连接和/或后端的机制。我搜索了很多地方,但找不到任何答案,因此,我们将不胜感激。


阅读 396

收藏
2020-05-10

共1个答案

小编典典

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

与使用常规时没有什么不同<form enctype="multipart/form-data">。您需要做的就是获取HTML5 /
JS代码,以multipart/form-data使用删除的文件发送请求,该请求与使用常规<input type="file">字段发送的请求完全相同。我假设您只是无法弄清楚如何使用HTML5 / JS实现这一目标。

您可以为此使用新的HTML5FileAPI,XHR2FormDataXMLHttpRequestUploadAPI。

这是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映射到的URL模式/uploadServlet。在此示例中,该文件随后以常规方式作为FileItem字段名称为的实例在ApacheCommons FileUpload中可用file


我使用以下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:

@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;
    }
}
2020-05-10