3

I'm uploading a CSV file to a Java servlet. My HTML form looks like this :

<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" name="submitBt" id="submitBt">
</form>

In my servlet, I do the following to retrieve the file :

public void uploadCsv(HttpServletRequest request) {
request.getPart("file")
...
}

When a file is set, the servlet does its work and everything is ok.

My problem is, I have a second form in the same JSP. So when a form is submitted, I want to test if the input named "file" containing the CSV file is set or not.

I tried the following :

if (req.getParameter("file") != null)

Always false

if (request.getParameterMap().containsKey("file"))

Always false too

if (req.getPart("file") != null)

Throws an exception if file not set

Help! D:

DonGelati
  • 43
  • 1
  • 9

3 Answers3

5

Forms parts are sent like a file to the server, so you can do this...

boolean isthereafile;
if(request.getPart("file").getSize()>0){
isthereafile = true;
}
if(request.getPart("file").getSize()<=0){
isthereafile = false;
}
ignemdev
  • 66
  • 1
  • 4
0

You need to annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work

Submitting an empty field is not the same as not submitting a field.

  • If a field is not filled out but submitted, end up as empty strings
  • If a field is not submitted at all then its null

so you can check if the value is not just an empty string

String file = request.getParameter("file");

if (file != null && !file.isEmpty()) {
    // It's submitted and filled
}

You can use accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).

<input type="file" accept=".csv" />

Note:

  • The accept attribute can only be used with <input type="file">
  • Do not use this attribute as a validation tool. File uploads should be validated on the server.

UPDATE

You can make file upload field mandatory using javascript validation

function validate(){
    var inputField = document.getElementById('upload');
    if(inp.files.length == 0){
        alert("Attachment Required");
        inputField.focus();
        return false;
    }
}
<form enctype="multipart/form-data" method="post" onsubmit="return(validate());">
    <input name="file[]" type="file" multiple="multiple" id="upload">
    <input type="submit" value="Submit"/>
</form>

Take a look at this answer How to upload files to server using JSP/Servlet?

rimonmostafiz
  • 1,341
  • 1
  • 15
  • 33
  • Thanks for your tip with accept=".csv" :) Unfortunatly (I tested again with your code), request.getParameter("file") is always null, even when a file is set in my form. Maybe becuse I'm using enctype="multipart/form-data" in my form... – DonGelati Jan 15 '18 at 08:09
  • Did you annotated your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work ? – rimonmostafiz Jan 15 '18 at 08:14
  • no unfortinaly, this is the same with or without @MultipartConfig. – DonGelati Jan 15 '18 at 08:17
  • Please take a look at the link I shared, It will help you. – rimonmostafiz Jan 15 '18 at 08:17
  • when using `@MultipartConfig` what `req.getPart("file")` returning ? – rimonmostafiz Jan 15 '18 at 08:19
  • It return the right content when I send a file using my form. It throws an exception if my form is empty – DonGelati Jan 15 '18 at 08:32
  • Which exception does it throw? – rimonmostafiz Jan 15 '18 at 09:17
  • A servletException :/ See: javax.servlet.ServletException: 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 – DonGelati Jan 15 '18 at 09:30
  • Thanks for your update! But in my case I don't want a mandatory input for my file upload : My page contains multiple forms, and I don't know in advance wich one will be filled by the user. For now I'm using my dirty try/catch technique (posted below)... – DonGelati Jan 15 '18 at 14:45
0

A (dirty) way to check if a Part is set, Since req.getPart("file") throws an exception :

boolean isSet = false;
try {
    req.getPart("file");
    isSet = true;
} catch(Exception e) { 
    isSet = false; 
}

if (isSet) {
    // Do your work
}
DonGelati
  • 43
  • 1
  • 9