File uploaded from jsp is not making it to servlet

38 Views Asked by At

I am attempting to upload a csv file from my JSP and used in the servlet request. I keep getting an exception in the servlet and it appears the file doesn't make it that far.

Here's part of my JSP. I've left out unnecessary parts:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<TABLE>
    <tr>
        <td>
            <form action="CIServlet" method="post">
                <input type="hidden" name="cN"
                       value="<%= request.getAttribute("cN") %>">
                Upload: <input type="file" name="fileName"  enctype="multipart/form data">
                <input type="submit" id="uploadFile" name="uploadFile" value="Upload CSV file">
            </form>
        </td>
    <tr>

</TABLE>
</body>

My servlet looks like this:

@WebServlet(name = "CIServlet", value = "/CIServlet")
@MultipartConfig
public class CIServletextends HttpServlet {

@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
                Part filePart = request.getPart("fileName");
} catch (IOException e) {
                response.getWriter().write("Failed to process CSV content due to " + e);
            } catch (ServletException e) {

                e.printStackTrace();
            }

When I submit the form, I get an exception:

javax.servlet.ServletException: The request content-type is not a multipart/form-data

request.getPart("fileName") is null when debugging. However if I evaluate request.getParameter("fileName") it has the file name.

I'm expecting request.getPart() to not be null. I'm using enctype="multipart/form data" on the file input. I'm also using @MultipartConfig annotation on my Servlet.

I've also made sure there's no JavaScript in my JSP that could be erasing the enctype.

1

There are 1 best solutions below

0
Roman C On

The attribute enctype="multipart/form data" should be set on <form> tag, not on the file input.

<form action="CIServlet" enctype="multipart/form data" method="post">
          <input type="hidden" name="cN" value="<%= request.getAttribute("cN") %>">
  Upload: <input type="file" name="fileName">
          <input type="submit" id="uploadFile" name="uploadFile" value="Upload CSV file">
</form>

If you need more information how to upload a file using servlet see Servlet receives null values after uploading a file.

In order to be able to get parameters and parts of files from a request, you can use the @MultipartConfig annotation:

An annotation that can be placed on the Servlet class indicating that servlet instances expect requests matching the type MIME with multipart/form-data.

Servlets annotated with MultipartConfig can retrieve Part components of a given multipart/form-data request, calling getPart() or getParts().