0

This is the Code which is sending the parameters fname selectedFile(byteArray) as part of the post request body from android to the tomcat server.

    public void uploadFile(){
        EditText filename=findViewById(R.id.fileName);
        //content://
        try {
            InputStream inputStream=getContentResolver().openInputStream(filePath);
            selectedFile= IOUtils.toByteArray(inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String purl="http://192.168.1.11:8080/placement/V2TryUploadFile";

        RequestBody requestBody=new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("fname",filename.getText().toString())
                .addFormDataPart("selectedFile",filename.getText().toString(),RequestBody.create(MediaType.parse("application/pdf"),selectedFile))
                .build();
        Request request=new Request.Builder()
                .url(purl)
                .post(requestBody)
                .build();

        Toast.makeText(MainActivity.this,filename.getText().toString(),Toast.LENGTH_SHORT).show();
        Toast.makeText(MainActivity.this,selectedFile.length+":",Toast.LENGTH_SHORT).show();
        OkHttpClient okHttpClient=new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,"Failed to Upload",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseString=response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,responseString,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

Servlet code (Running on tomcat server) to handle the post request sent from the android add

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String fname=request.getParameter("fname")+".pdf";
        Part selectedFile=request.getPart("selectedFile");
        System.out.println(fname);
        System.out.println(selectedFile+"");
        InputStream filecontent = selectedFile.getInputStream();

        byte[] fileAsByteArray = IOUtils.toByteArray(filecontent);

        FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\VAISHAK`\\placeWorkSpace\\placement\\ResumeUploads\\" + fname);
        imageOutFile.write(fileAsByteArray);
        imageOutFile.close();
        doGet(request, response);
    }

The issue is fname and selectedFile are not shown null in android app , but both are shown as null in the tomcat server console.

Also Below is the tomcat server log in eclipse

null.pdf
null
Apr 13, 2020 11:56:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [trial.V2TryUploadFile] in context with path [/placement] threw exception
java.lang.NullPointerException
    at trial.V2TryUploadFile.doPost(V2TryUploadFile.java:49)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:615)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:818)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1623)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Sana Ebadi
  • 6,656
  • 2
  • 44
  • 44
  • You have a `NullPointerException`. So tell us what is `null`. And in which statement. – blackapps Apr 13 '20 at 19:16
  • Do not use a pointer that is null. Check for null before use. – blackapps Apr 13 '20 at 19:19
  • @blackapps the problem is.why the post request parameters are null in the servlet. But they are not null when I am sending from the android app in okhttp request – karthik iyer Apr 13 '20 at 19:37
  • @blackapps ``` String fname=request.getParameter("fname")+".pdf"; Part selectedFile=request.getPart("selectedFile"); ``` the above two variabless are null Due to which the subsequent code throws null pointer exception – karthik iyer Apr 14 '20 at 04:24
  • String fname=request.getParameter("fname")+".pdf"; Part selectedFile=request.getPart("selectedFile"); . As These Statements are null in the servlet, subsequents statements are throwing null pointer exception @blackapps.. sorry is it clear now – karthik iyer Apr 14 '20 at 07:35
  • InputStream filecontent = selectedFile.getInputStream(); – karthik iyer Apr 14 '20 at 07:53
  • `.setType(MultipartBody.FORM)` Maybe the type is wrong. Did you try doGet() to see if the parameters are there? – blackapps Apr 14 '20 at 08:14
  • https://stackoverflow.com/questions/2349633/doget-and-dopost-in-servlets Have you looked at the third comment? – blackapps Apr 14 '20 at 08:15
  • @blackapps.. You were right the .setType(MutipartBody.FORM) is wrong. This was because the servlet was not declared for MutipartBody. When i added the annotation "@MultipartConfig" to the servlet , it worked – karthik iyer Apr 14 '20 at 08:51

1 Answers1

0

I finally figured out the solution

The servlet by default does not handle

MutipartBody FORM

So in order for it to support that, we need to add the below annotataion to the servlet

@MultipartConfig