9

I have the following HTML form:

<form enctype="multipart/form-data" method="post" action="/myservlet">
    <input type="file" name="mptest">
    <br />
    <input type="submit" value="upload">
 </form>

And I have the following servlet which I created based on this answer:

package com.functions;

import java.io.*;
// import java.sql.Connection;
// import java.sql.PreparedStatement;
// import java.sql.ResultSet;
// import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

// import com.functions.utility.DBConnector;
public class restore extends HttpServlet {

    private static final long serialVersionUID = 8097085789553030042L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--------------------");
        System.out.println(" On restore.java ");
        System.out.println("--------------------");
        try {
            fetchDataFromDB(request, response);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void fetchDataFromDB(HttpServletRequest request,
            HttpServletResponse response) throws InterruptedException,
            IllegalStateException, ServletException {
        try {
            System.out.println("Test 1");
            for (Part part : request.getParts()) {
                String filename = getFilename(part);
                System.out.println("Test 2");
                if (filename == null) {
                    System.out.println("Test 3");
                    // Process regular form field (input
                    // type="text|radio|checkbox|etc", select, etc).
                    String fieldname = part.getName();
                    System.out.println(fieldname);
                    String fieldvalue = getValue(part);
                    System.out.println(fieldvalue);
                    // ... (do your job here)
                } else if (!filename.isEmpty()) {
                    System.out.println("Test 4");
                    // Process form file field (input type="file").
                    String fieldname = part.getName();
                    System.out.println(fieldname);
                    filename = filename
                            .substring(filename.lastIndexOf('/') + 1)
                            .substring(filename.lastIndexOf('\\') + 1); // MSIE
                                                                        // fix.
                    InputStream filecontent = part.getInputStream();
                    System.out.println(filecontent);
                    String[] command = new String[] {
                            "C:/Program Files (x86)/MySQL/MySQL Server "
                            + "5.5/bin/mysql",
                            "--user=root", "--password=root", "dummy", "-e",
                            "source "+"C:/Users/John/Desktop/LMS/backup.sql" };
                    Process restore = Runtime.getRuntime().exec(command);
                    int check = restore.waitFor();
                    System.out.println(check);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                return cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
            }
        }
        return null;
    }

    private static String getValue(Part part) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                part.getInputStream(), "UTF-8"));
        StringBuilder value = new StringBuilder();
        char[] buffer = new char[1024];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            value.append(buffer, 0, length);
        }
        return value.toString();
    }
}

But the for loop on request.getParts() is never entered. How is this caused and how can I solve it?

Community
  • 1
  • 1
John
  • 4,413
  • 6
  • 25
  • 28
  • possible duplicate of [How to upload files in JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824) – BalusC Sep 16 '11 at 14:55
  • My answer to the question which you linked mentions at the bottom some links as to how to process the uploaded file in JSP/Servlet. – BalusC Sep 16 '11 at 14:56
  • I did try the suggestion you made in the link.... but it doesnt even enter the for loop..... – John Sep 16 '11 at 15:31

1 Answers1

20

If you want to use Servlet 3.0 HttpServletRequest#getParts(), then you must annotate your servlet with @MultipartConfig.

@WebServlet(urlPatterns={"/myservlet"})
@MultipartConfig
public class Myservlet extends HttpServlet {

    // ...
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • still gives me backup.sql and not C:/Users/John/Desktop/LMS/backup.sql – John Sep 16 '11 at 16:23
  • 3
    Why in earth do you need the full path? Read http://stackoverflow.com/questions/81180/how-to-get-the-file-path-from-html-input-form-in-firefox-3/3374408#3374408 Just get the file content and save it to server's disk and then invoke your command on the path of the saved file. – BalusC Sep 16 '11 at 16:24
  • Adding the annotation `@MultipartConfig` didn't help in my case (Tomcat 7.0.70 with Servlet 3.0) – basZero Sep 23 '16 at 13:54