如何将数据从servlet发布到Javascript或如何将上传的字节从servlet发布到HTML

时间:2014-12-17 17:53:33

标签: java javascript html servlets upload

我想将文件上传到服务器,但我不明白:如何将数据从servlet发布到javascipt或如何将上传的字节从servlet发布到html。上传文件的类是UploadFileServlet,在consol-UploadStream和form-uploadFile.html中输出的类。 UploadStream将数据打印到consol,但我想将此数据重定向到html-form并打印。

UploadStream

public static class UploadStream extends FilterOutputStream {

    final ProgressListener listener;
    private long transferred;
    public long bytes;

    public UploadStream(final OutputStream out, final ProgressListener listener) {
        super(out);
        this.listener = listener;
        this.transferred = 0;
    }

    public void write(byte[] b, int off, int len) throws IOException {
        out.write(b, off, len);
        bytes = this.transferred += len;
        System.out.println(this.transferred / 1024 + " KB");
    }

    public void write(int b) throws IOException {
        out.write(b);
        this.transferred++;
    }

    public void getBytes(HttpServletRequest request) throws ServletException, IOException {
        request.setAttribute("bytes", bytes);            
    }
}

UploadFileServlet

public class UploadFileServlet extends HttpServlet {
    private boolean isMultipart;    
    //Maximum file size, 2gb
    private final int maxFileSize = 1024 * 1024 * 2000;
    //Maximum memory size, 3gb
    private final int maxMemSize = 1024 * 1024 * 3000;
    private File fileToSave;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException  {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);        
        response.setContentType("text/html;charset=UTF-8");
        isMultipart = ServletFileUpload.isMultipartContent(request);        
        java.io.PrintWriter out = response.getWriter();
        if (!isMultipart) {
            out.println("<h1>No file uploaded</h1>");
            return;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);        
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);
            // Process the uploaded file items
            Iterator i = fileItems.iterator();
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    String contentType = fi.getContentType();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        fileToSave = new File(this
                                + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        fileToSave = new File(this
                                + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    fi.write(fileToSave);
                }
            }
        } catch (Exception ex) {
            out.println(ex.getMessage());
        }
        /* TODO output your page here. You may use following sample code. */        
        out.println("Image uploaded!");    
        File file = new File(fileToSave.getAbsoluteFile().toString());        
        String date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date (System.currentTimeMillis()));       
        HttpParams params = new BasicHttpParams();
        params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(getUrl()+"upload.php");        
        MultipartEntity reqEntity = new MultipartEntity(){
        ProgressListener listener; 
                public void writeTo(final OutputStream outstream) throws IOException {
                    super.writeTo(new UploadStream(outstream,listener));            
                }
            };
        FileInputStream fis  = new FileInputStream(file);
        autorization(reqEntity,"upload");
        reqEntity.addPart("title", new StringBody(date));
        reqEntity.addPart("media", new InputStreamBody(fis, file.toString()));
        post.setEntity(reqEntity);
        HttpResponse httpResponse = client.execute(post);
        HttpEntity resEntity = httpResponse.getEntity();
        InputStream inputStream = resEntity.getContent();
        String resultString = ProjectLibrary.convertStreamToString(inputStream);
        //request.setAttribute("bytes", "");
            String url = "/WEB-INF/jsp/resultsUploadFile.jsp";
            request.getRequestDispatcher(url).forward(request, response);
        file.delete();
    }    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

HTML:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Multiple file uploader</title>
        <script>
            var totalFileLength, totalUploaded, fileCount, filesUploaded;

            function debug(s) {
                var debug = document.getElementById('debug');
                if (debug) {
                    debug.innerHTML = debug.innerHTML + '<br/>' + s;
                }
            }

            function onUploadComplete(e) {
                totalUploaded += document.getElementById('files').
                        files[filesUploaded].size;
                filesUploaded++;
                debug('complete ' + filesUploaded + " of " + fileCount);
                debug('totalUploaded: ' + totalUploaded);
                if (filesUploaded < fileCount) {
                    uploadNext();
                } else {
                    alert('Finished uploading file(s)');
                }
            }

            function onFileSelect(e) {
                var files = e.target.files; // FileList object
                var output = [];
                fileCount = files.length;
                totalFileLength = 0;
                for (var i = 0; i < fileCount; i++) {
                    var file = files[i];
                    output.push(file.name, ' (',
                            file.size, ' bytes, ',
                            file.lastModifiedDate.toLocaleDateString(), ')'
                            );
                    output.push('<br/>');
                    debug('add ' + file.size);
                    totalFileLength += file.size;
                }
                document.getElementById('selectedFiles').innerHTML =
                        output.join('');
                debug('totalFileLength:' + totalFileLength);
            }

            function onUploadProgress(e) {
                if (e.lengthComputable) {
                    var percentComplete = parseInt(
                            (e.loaded + totalUploaded) * 100
                            / totalFileLength);
                    var bar = document.getElementById('bar');
                    bar.style.width = percentComplete + '%';
                    bar.innerHTML = percentComplete + ' % complete';
                } else {
                    debug('unable to compute');
                }
            }

            function onUploadFailed(e) {
                alert("Error uploading file:" + e);
            }

            function uploadNext() {
                var xhr = new XMLHttpRequest();
                var fd = new FormData();
                var file = document.getElementById('files').files[filesUploaded];
                fd.append('media', file);
                xhr.upload.addEventListener("progress", onUploadProgress, false);
                xhr.addEventListener("load", onUploadComplete, false);
                xhr.addEventListener("error", onUploadFailed, false);
                debug('uploading ' + file.name);
                xhr.open('POST', 'UploadFileServlet', true);
                xhr.send(fd);
            }

            function startUpload() {
                totalUploaded = filesUploaded = 0;
                uploadNext();
            }
            window.onload = function () {
                document.getElementById('files').addEventListener(
                        'change', onFileSelect, false);
                document.getElementById('uploadButton').
                        addEventListener('click', startUpload, false);
            }

        </script>        
    </head>
    <body>        
        <h1>Multiple file uploader</h1>
        <div id='progressBar' style='height:20px;border:2px solid green'>
            <div id='bar' 
                 style='height:100%;background:#33dd33;width:0%'>
            </div>
        </div>
        <form id='form1' action="UploadFileServlet" 
              enctype="multipart/form-data" method="post">    
            <input type="file" id="files" multiple/>
            <br/>
            <output id="selectedFiles"></output>
            <input id="uploadButton" type="submit" value="Upload"/>
        </form>
        <div id='debug' 
             style='height:100px;border:2px solid green;overflow:auto'>
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

通常,Web应用程序(或网页)与servlet之间的通信将在两端实现。

jQuery为许多后端调用提供了有用的API文档。主要是POST和GET调用。你可以找到API here。您需要识别要与之通信的servlet,文档应该为此提供充分的解释。

然后,对于servlet,您需要实现一种检索POST / GET调用的方法。您在上面创建的servlet看起来很稳固。它只需要被赋予一个唯一的标识符,以便来自前端的任何调用都可以针对该不同的类。

的内容
@WebServlet("UploadServlet")
public class UploadFileServlet extends HttpServlet {

我相信你只需要更新HTML / Javascript。看看jQuery的API,你应该掌握它。

我会建议您正确转换文件后,将其包含在JSON格式中(即:var json = {}; json.section =&#34;示例&#34 ;;)以便您可以传递额外的数据。但主要是JSON是用于在前端和后端之间发送数据的最常用格式。

JSON格式如下所示:

{ 部分:&#34;示例&#34; }

您可以根据需要在JSON中添加任意数量的参数。只要确保你没有添加任何你不需要的东西。最好尽量保持JSON的大小。但有时无法避免。

我已经使用ajax调用对servlet执行文件POST。

例如它看起来像这样:

$.ajax({
  type: "POST",
  url: "UploadServlet",
  data: { fileContents: fileVariable }
});

您可以在JavaScript中轻松创建JSON:

var json = {};
json.fileContents = convertFile;

然后你只需将ajax调用更新为

$.ajax({
  type: "POST",
  url: "UploadServlet",
  data: json
});

这不是一个完整的解决方案,但我相信它解决了我看到的一些问题。