Reputation: 1383
I have a simple form with enctype "multipart"; I am using this to upload an image to my server. I have two possible solutions, but neither of them are complete.
First solution:
FileItemIterator iterator = upload.getItemIterator( request );
while( iterator.hasNext() ){
FileItemStream item = iterator.next();
if( item.isFormField() ){
// store IMG
}
} // ~while( iter.hasNext() )
In this solution, I can't get the dimensions of the uploaded file, but I can get if it's a form field or not (using item.isFormField()
)
My second solution uses the Servlet 3.0 API:
for( Part part: request.getParts() ){
System.out.println( part.getSize() );
}
Here I can get the size of the uploaded image, but I can't tell whether it's a simple form field or not.
What am I missing?
What you need for help me?
Upvotes: 1
Views: 738
Reputation:
As mentioned in the documentation of the FileItemStream
the isFormField() method tells whether if this is a simple form field returns true , otherwise return false .
so for upload image it will return false
so you should do the following :
if(! item.isFormField() ){
// store IMG
}else {
//simple form field.
}
and refer to this answer here to see how to convert an InputStream to byte[] to know how many bytes are there in your uploaded file .
if you are using servlet 3 do like the following :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username= request.getParameter("username"); // Retrieves <input type="text" name="username">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String filename = filePart.getName();
InputStream filecontent = filePart.getInputStream();
// ... (do your job here)
}
and give me some feedback .
Hope that helps .
Upvotes: 1