HTML5文件上传到Java Servlet

时间:2011-08-18 21:01:10

标签: java html5 servlets file-upload

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

我知道如何使HTML5 DnD正常工作,但我无法弄清楚Java Servlet连接和/或后端的机制。我搜索了很多地方,但我找不到任何答案,所以对任何帮助都表示赞赏。

2 个答案:

答案 0 :(得分:45)

  

我知道如何让HTML5 DnD正常工作,但我无法弄清楚Java Servlet连接和/或后端的机制。

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

您可以使用新的HTML5 File API,XHR2 FormDataXMLHttpRequestUpload API。

以下是您的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


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

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

另见:

答案 1 :(得分:-1)

您需要多部分配置,例如:

@MultipartConfig(fileSizeThreshold = 1024 * 1024, 
                 maxFileSize = 1024 * 1024 * 5, 
                 maxRequestSize = 1024 * 1024 * 5 * 5)

就我而言,它仅适用于此配置。