Announcement Announcement Module
Collapse
No announcement yet.
File Upload Issue. FileItemIterator's hasNext() method always returns false. Why? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • File Upload Issue. FileItemIterator's hasNext() method always returns false. Why?

    Hey all,

    I am using the Apache's Common FileUpload, Spring 2.5 and Uploadify Javascript plugin to upload multiple files at once. The following code used to work fine previously. However, its not working since yesterday!

    The issue is, The FileItemIterator's hasNext() method is always returning false. i,e. (while (iter.hasNext()) is always returning false).

    Can someone please point me in the right direction so that I can weed this bug out.

    Many thanks,
    Joe.



    Code:
    public class FileUploadProcessController implements Controller {
        protected final Log logger = LogFactory.getLog(getClass());
    
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        	throws ServletException, IOException, FileUploadException {
            logger.info("Inside FileUploadProcessController");
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (! isMultipart) return null;
           
            //debug
            logger.info("Is a multipart request!");
            
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();        
            // Parse the request
            FileItemIterator iter;
    		try {
            	//debug
            	logger.info("Getting Iterator...");
    			iter = upload.getItemIterator(request);
    	        while (iter.hasNext()) {
    	            FileItemStream item = iter.next();
    	            String name = item.getFieldName();
    	            
    	            InputStream inputStream = item.openStream();
    	            if (item.isFormField()) {
    	                String fieldValue = Streams.asString(inputStream);
    	                //debug
    	                logger.info("Form field " + name + " with value " + fieldValue + " detected.");
    		            inputStream.close();
    	            } else {
    	            	//debug
    	                logger.info("File field " + name + " with file name " + item.getName() + " detected.");
    	                // Process the input stream
    	                File originalFile = FileUtil.getUniqueFile("c:/", StringUtil.getFileName(item.getName()));
    	                try {
    	                	uploadToFile(inputStream, originalFile);
    	                } catch (FileNotFoundException ex) {
    	                	logger.error(ex);
    	                	throw ex;
    	                }  catch (IOException ex) {
    	                	logger.error(ex);
    	                	throw ex;
    	                }
    	                inputStream.close();
    	                logger.info("File uploaded successfully!");
    	            }
    	        }        
    		} catch (Exception ex) {
    			logger.error(ex);
    			throw new RuntimeException(ex);
    		}
    
            return new ModelAndView("success");
        }
    
    	// Private methods
        private void uploadToFile(InputStream inputStream, File file) throws FileNotFoundException, IOException {
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int bytesRead = -1;
            do {
            	bytesRead = inputStream.read(bytes);
            	if (bytesRead != -1) outputStream.write(bytes, 0, bytesRead);
            } while (bytesRead != -1);
            outputStream.flush();
            outputStream.close();    	
        }
        
    }
    Code:
    <html>
    <head>
    <title>Upload files</title>
    <script src="/uploadify/swfobject.js" />" type="text/javascript"></script>
    <script src="/uploadify/jquery.uploadify.v2.1.0.min.js" />" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="/uploadify/uploadify.css" >
    <script type="text/javascript">
    $().ready(function(){
    	$('#file').uploadify({
    		'uploader': '/uploadify/uploadify.swf',
    		'script': '/filepload/',
    		'scriptData': {'userId': ${model.userId}},
    		'folder': '/BLAH',
    		'cancelImg': '/uploadify/cancel.png',
    		'multi': true,
    		'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
    		'fileDesc': '*.jpg;*.jpeg;*.gif;*.png (Image files only!)',
    		'sizeLimit': ${model.fileSizeLimit},
    		onAllComplete: function(event, data) {window.location="/recentuploads/";} 
    	});
    });
    </script>
    </head>
    <body>
    <div class="content">
    	<div class="form-div">
    	<form method="post" action="/fileupload/" enctype="multipart/form-data" >
    		<fieldset>
    			<legend>Upload Files</legend>
    			<input id="file" name="file" type="file" size="50" />
    			<br />
    			<a href="javascript:$('#file').uploadifyUpload();">Upload Files</a>
    		</fieldset>
    	</form>
    	</div>
    </div> 
    </body>
    </html>

  • #2
    I got around the issue by avoiding the Commons File Upload Streaming API. I had to map the request to a MultipartHttpServletRequest object to get the job done.

    Code:
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    final Map<String, MultipartFile> files = (Map<String, MultipartFile>) multiRequest.getFileMap();
    for (MultipartFile file : files.values()) {	        	
      ...
    }

    Comment


    • #3
      Do you still have the code you put inside the for loop? I've the exact same issue specifically with Weblogic 12 only.
      Thanks!

      Originally posted by joehansen View Post
      I got around the issue by avoiding the Commons File Upload Streaming API. I had to map the request to a MultipartHttpServletRequest object to get the job done.

      Code:
      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
      final Map<String, MultipartFile> files = (Map<String, MultipartFile>) multiRequest.getFileMap();
      for (MultipartFile file : files.values()) {	        	
        ...
      }

      Comment

      Working...
      X