servlet upload file Direct processing mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.