2

I tried to create file uploader in java. This is working but with redirecting to to servlet, I want to do it without reloading page. so I tried this way.

test.js

$(document).ready(function() {
$('#btn').click(function() {
    $.ajax({
        type: 'post',
        url : '../FileUploadServlet2',
        data : {
            picture : $('#picture').val()
        },
        success : function(responseText) {
            $('#ajaxGetUserServletResponse').text(responseText);
        }
    });
}); });

Test.jsp - body

<form id="myform" method="post" enctype="multipart/form-data">
    Enter Image: <input type="file" id="picture" />
    <input type="hidden" value="true" name="submit">
    <input id="btn" type="button" value="Click">
</form>
<br>
<br>

<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>

FileUploadServlet2

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Here");

    processRequest(request, response);

}

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    // location where file are uploaded
    String destination = "/home/dhanushka/test2";
    // creates a file in the given location

    // Create path components to save the file
    final String path = destination;
    // get the part of the profile picture file
    final Part filePart2 = request.getPart("picture");
    // gets only the file name
    final String fileName2 = getFileName(filePart2);

    // upload the profile picture
    try {
        writer = response.getWriter();
        uploadProcess(fileName2, path, filePart2);
        writer.write("Uploaded");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(content.indexOf('=') + 1).trim()
                    .replace("\"", "");
        }
    }
    return null;
}

private void uploadProcess(String fileName, String path, Part filePart)
        throws Exception {
    try {
        out = new FileOutputStream(new File(path + File.separator
                + fileName));

        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        /* writer.println("New file " + fileName + " created at " + path); */
        LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
                new Object[] { fileName, path });
    } catch (FileNotFoundException fne) {
        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        writer.println("<br/> ERROR: " + fne.getMessage());

        LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
                new Object[] { fne.getMessage() });

    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }

    }
}}

This returns the error.

Oct 31, 2015 1:33:24 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [com.sms.upload.FileUploadServlet2] in context with path [/SMS] threw exception [org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8] with root cause org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8 at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.(FileUploadBase.java:800) at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256) at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280) at org.apache.catalina.connector.Request.parseParts(Request.java:2730) at org.apache.catalina.connector.Request.getParts(Request.java:2641) at org.apache.catalina.connector.Request.getPart(Request.java:2818) at org.apache.catalina.connector.RequestFacade.getPart(RequestFacade.java:1089) at com.sms.upload.FileUploadServlet2.processRequest(FileUploadServlet2.java:75) at com.sms.upload.FileUploadServlet2.doPost(FileUploadServlet2.java:60) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
dhanushkac
  • 520
  • 2
  • 8
  • 25

2 Answers2

0

You should set the contentType option to false and has to use the FormData class, contentType option forcing jQuery not to add a Content-Type header, otherwise the boundary string will be missing.

You must also leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

Your test.js file has to be like;

$(document).ready(function() {

    $('#btn').click(function() {
        event.preventDefault();

        var form = $('#myform')[0];
        var data = new FormData(form);

        $.ajax({
            type : "POST",
            enctype : 'multipart/form-data',
            url : '../FileUploadServlet2',
            data : data,
            processData : false,
            contentType : false,
            cache : false,
            success : function(responseText) {
                $('#ajaxGetUserServletResponse').text(responseText);
            }
        });
    }); 
});

And at the server side code, for the Servlet class you need to add @MultipartConfig

@WebServlet("/FileUploadServlet2")
@MultipartConfig
public class FileUploadServlet2 extends HttpServlet {
    ----------
}
0

Error : Unable to parse upload request: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8

Solution : If you are using form with aui Request than follow below solution :

AUI().use('aui-base', 'io', 'aui-io-request', function(A){
        A.io.request('${resourceURL}', {
               method: 'post',
               enctype : 'multipart/form-data',
               upload : true,
               data: {
                   "<portlet:namespace />sectionName" : sectionName,
                   "<portlet:namespace />subSectionName" : subSectionName,
               },
               form:{
                   id:'personalDetailsForm',upload: true
               },
               on: {
                       success: function() {
                        alert(this.get('responseData'));
                   }
              }
        });
    });
Parth
  • 126
  • 5