PackageCom.isoftstone.eply.servlet;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.FileWriter;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.PrintWriter;ImportJava.io.StringReader;Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.Map;ImportJava.util.UUID;ImportJavax.activation.DataHandler;ImportJavax.activation.DataSource;ImportJavax.activation.FileDataSource;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;Importcom.isoftstone.eply.util.ChangeFileToString;ImportCom.isoftstone.eply.util.CheckElectronicPolicy;Importcom.isoftstone.eply.util.CreateCheckXml;ImportCom.isoftstone.eply.vo.EPlyResponseFileVo;ImportCom.isoftstone.eply.vo.EPlyResponseVo;Importcom.isoftstone.fwk.util.SpringUtils; Public classElectroicpolicyuploadfileservletextendsHttpServlet { Public voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, ioexception{ This. DoPost (request, response); } Public voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//get uploaded files to save the directory, the uploaded files in the Web-inf directory, do not allow direct access to the outside world, to ensure the security of uploading filesString Savepath = This. Getservletcontext (). Getcontextpath () + "/upload";File File =NewFile (Savepath); //determine if the saved directory for the uploaded file exists if(!file.exists () &&!file.isdirectory ()) {System.out.println (Savepath+ "Directory does not exist, need to create"); //Create a directoryFile.mkdir (); } String Message= "";//message Prompt Try{ //Use the Apache File Upload component to process file upload steps://1. Create a diskfileitemfactory factoryDiskfileitemfactory factory =Newdiskfileitemfactory (); //2. Create a file Upload parserServletfileupload upload =Newservletfileupload (Factory); //solve the Chinese characters of uploading file nameUpload.setheaderencoding ("UTF-8"); //3, determine whether the submitted data is the upload form data if(!servletfileupload.ismultipartcontent (Request)) { //get data in the traditional way return ; } //4, using the Servletfileupload parser to parse the upload data, the results of the analysis returned is a list<fileitem> collection, each fileitem corresponding to a form form inputlist<fileitem> list =upload.parserequest (Request); for(Fileitem item:list) {//if the data in the Fileitem is encapsulated in an ordinary entry if(Item.isformfield ()) {String name=Item.getfieldname (); //solve the problem of Chinese garbled data of ordinary input itemsString value = item.getstring ("UTF-8"); //value = new String (value.getbytes ("iso8859-1"), "UTF-8");SYSTEM.OUT.PRINTLN ("Normal input name and data" +name + "=" +value); Cplyno=value; }Else{//If the upload file is encapsulated in Fileitem//get the uploaded file name,String filename =item.getname ();if(filename==NULL|| Filename.trim (). Equals ("")){ Continue; } //Note: Different browser submissions are not the same file name, some browsers submitted by the file name is with a path, such as: C:\a\b\1.txt, and some just simple file name, such as: 1.txt//handles the path portion of the file name of the uploaded files that are obtained, leaving only the file name sectionfilename = filename.substring (filename.lastindexof ("\ \") +1); //gets the input stream of the upload file filename in itemInputStream in =Item.getinputstream (); //Create a file output streamFileOutputStream out =NewFileOutputStream (Savepath + "/" +filename); //Create a buffer byteBuffer[] =New byte[1024]; //identifies whether the data in the input stream has been read out intLen = 0; //The loop reads the input stream into the buffer, and (len=in.read (buffer)) >0 indicates that there is data in it. while(Len=in.read (buffer)) >0){ //writes the data of the buffer to the specified directory (savepath + "\ \" + filename) using the FileOutputStream output streamOut.write (buffer, 0, Len); } //close the input streamIn.close (); //turn off the output streamOut.close (); //Delete temporary files generated when processing file uploadsItem.delete (); UUID UUID=Uuid.randomuuid (); //get the ID generated by the objectString Resid =uuid.tostring ();
String XMLData= "<?xml version=\" 1.0\ "encoding=\" gbk\ "? ><packet>//Spell MessageFile xmlfile=NewFile (Savepath + "/" +resid+ ". xml");//saving XML Format Files if(!Xmlfile.getparentfile (). exists ()) Xmlfile.getparentfile (). Mkdirs (); BufferedReader BufferedReader=NewBufferedReader (NewStringReader (XMLData)); BufferedWriter BufferedWriter=NewBufferedWriter (NewFileWriter (xmlfile)); CharBuf[] =New Char[1024];//character Buffers intLen2; while((Len2 = Bufferedreader.read (BUF))! =-1) {bufferedwriter.write (buf,0, Len2); } bufferedwriter.flush (); Bufferedreader.close (); Bufferedwriter.close (); DataSource Source=NewFiledatasource (xmlfile); DataHandler DataHandler=NewDataHandler (source); Eplyresponsevo Epresponse=NewEplyresponsevo (); List<EPlyResponseFileVo> Listvo =NewArraylist<eplyresponsefilevo>();File File=NewFile (Savepath + "/" +filename);DataSource Source2=Newfiledatasource (file); DataHandler DataHandler2=NewDataHandler (SOURCE2);Xmlfile.delete (); //Delete temporary filesFilepdf.delete ();//Delete temporary files }Catch(Exception e) {if("". Equals (Message)) {Message= "Upload file failed, please re-upload!" "; } e.printstacktrace (); } response.setcontenttype ("text/html;charset=gb2312"); PrintWriter out=Response.getwriter (); Out.println ("<script type= ' text/javascript ' >alert ('" +message+ "') </script>"); Out.print ("<script language=javascript>window.close ();"); Out.print ("</script>"); Out.close (); }}
Servlet implements uploading files and simultaneously writing XML format files and uploads