0

I want to upload files to server, but I don't understand:How post data from servlet to javascipt or how post uploaded bytes to html from servlet. Class, who upload file is UploadFileServlet, class who out in consol-UploadStream and form-uploadFile.html. UploadStream print data to consol, but I want to redirect this data to html-form and print.

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>
}

The 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>
Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Serg Bash
  • 91
  • 1
  • 12

1 Answers1

1

Generally, communication between a web application (or web page) to a servlet would be implemented on both ends.

jQuery has useful API document for many calls to the backend. Primarily POST and GET calls would be made. You can find the API here. You would need to identify the servlet you want to communicate with, the documentation should provide sufficient explanation on that end.

Then for the servlet you need to implement a way to retrieve the POST/GET calls. The servlet you created above looks solid. It just needs to be given a unique identifier so that any calls from the frontend can target that distinct class.

Something along the lines of

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

I believe you just need to update the HTML/Javascript. Look at the API for jQuery and you should get a handle on it.

I would recommend once you converted the file properly, to include it in a JSON format (ie: var json = {}; json.section = "example";) so that you could either pass additional data. But mainly JSON is the most common format used to send data between the frontend and the backend.

The JSON format would look like this:

{ section: "example" }

You could add as many parameters within JSON as you want. Just make sure you don't add any you don't need. It's always best to keep the size of the JSON as slim as possible. But sometimes it cannot be avoided.

I have used the ajax call to do a POST of a file to a servlet.

For example it looked like this:

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

You can create a JSON easily in JavaScript:

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

Then you just update the ajax call to be

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

This isn't a complete solution, but I believe it addresses some of the issues I saw.

Aggieborn
  • 312
  • 2
  • 8