Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if HttpServletRequest getPart("...") is set or not

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:

like image 776
DonGelati Avatar asked Mar 14 '26 17:03

DonGelati


1 Answers

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;
}
like image 149
ignemdev Avatar answered Mar 17 '26 07:03

ignemdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!