In the process of development, often encountered in the way of File upload batch processing of data, previously encountered the situation is to save the file to the local temporary file, and then use the POI way to handle, but in fact, the operation process is simply read operation, so it is not so complicated, The following document describes how the servlet's Javax.servlet.http.Part package is used to handle this function. The code is as follows:
Part Part=request.getpart ("label name"); String filename=getfilename (Part.getheader ("Content-disposition") ); Boolean ResultCode=true; StringBuffer result=NewStringBuffer (); //Checksum if(stringhelper.isempty (filename)) {Result.append ("Please upload file"); ResultCode=false; }Else if(!filename.endswith ("CSV") {result.append ("Upload file only supports CSV"); ResultCode=false; } if(resultcode) {BufferedReader reader=NewBufferedReader (NewInputStreamReader (Part.getinputstream ())); String Line=NULL; Booleanisfirst=true; while(line = Reader.readline ())! =NULL) { if(!IsFirst) {Result.append (line). Append (","); }Else{IsFirst=false; } } if(0<result.length ()) {Result=result.delete (Result.length ()-1, Result.length ()); }} response.setcontenttype ("Text/html;charset=utf-8"); Response.getwriter (). Print ("<script type= ' text/javascript ' >parent.callback ('" +result.tostring () + "', '" +resultcode+ "');</script> "); Response.getwriter (). Close (); return;
Private string GetFileName (string header) { if(! Stringhelper.isempty (header)) { = Header.split (";") ); = Temparr1[2].split ("="); = Temparr2[1].substring (temparr2[1].lastindexof ("\ \") +1). ReplaceAll ("\" "," ") ; return fileName; } Else { return ""; } }
servlet upload file Direct processing mode