How to detect if a form input element of type file is empty
I have some code which reads a file through a form field of type file
<input type="file" ... />
I want to give the user another option of providing a url to a file rather than having to upload it as ma开发者_StackOverflow社区ny are already online.
How can I detect when this field is empty on the server side. I am using Apache Commons FileUpload
FileItemStream item = iter.next();
name = item.getFieldName();
stream = item.openStream();
if(!item.isFormField()){
if(item.toString()!=""){
....
I need to detect when item
is empty. The above code doesn't work, nor does using:
if(item.equals(null)){
....
You can't call item.equals( null )
when item is null. You have to test it like this:
if( item == null ) {
...
}
To check for any empty file input in the form while uploding any file to the server best way follow my instructions 1. use @MultipartConfig() at the top of your servlet class 2. add the following method to your class
private InputStream getImageStream(HttpServletRequest request, String image){
try {
Part part = request.getPart(image);
String header = part.getHeader("content-disposition");
InputStream input = null;
if(header.contains("filename")){
input = part.getInputStream();
}
return input;
} catch (IOException | ServletException e ){
e.printStackTrace();
}
return null;
}
Code description
- The code get the file using build in class "Part"
- After that it will assign the all contents of the object part the we call using request.getPart(image), Where "image" is the name of the file input in your form field. And assign it to String object "header"
- If you uplode any file to the input field the "header" will contain a sub sting "filename" and if it does it means you upload a file and assign it to InputStream object input else the is no file and the InputStream input will be assigned to null by default
return the InputStream object
And in your get or post method call the above method with the code below
InputStream school_pic = getImageStream(request, "schoolPic");
where "schoolPic" is the name of your input file in the form
That is all gusy
精彩评论