Importjavax.servlet.*;Importjavax.servlet.http.*;ImportJava.io.*;ImportJava.util.*;Importjava.util.regex.*;Importorg.apache.commons.fileupload.*; Public classUploadextendsHttpServlet {Private Static FinalString content_type = "text/html; Charset=utf-8 "; //Process the HTTP Post request Public voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype (content_type); PrintWriter out=Response.getwriter (); Try{diskfileupload Fu=Newdiskfileupload ();//set allow user to upload file size in bytes, set to 2mFu.setsizemax (2*1024*1024); //set up to allow only data stored in memory, Unit: bytesFu.setsizethreshold (4096); //set the directory where the data is stored in the hard disk once the file size exceeds the value of Getsizethreshold ()Fu.setrepositorypath ("C://windows//temp"); //start reading upload informationList Fileitems =fu.parserequest (request);//process each uploaded file in turnIterator iter =fileitems.iterator ();//regular match, filter path take file nameString regexp= ". +////(. +) $";//filter out the file typesString[] errortype={". exe", ". com", ". CGI", ". asp"}; Pattern P=Pattern.compile (REGEXP); while(Iter.hasnext ()) {Fileitem Item=(Fileitem) iter.next (); //ignore any other form information that is not a file field if(!Item.isformfield ()) {String name=Item.getname (); LongSize =item.getsize (); if((name==NULL|| Name.equals ("")) && size==0) Continue; Matcher m=P.matcher (name); Booleanresult =M.find (); if(Result) { for(intTemp=0;temp<errortype. LENGTH; temp++){ if(M.group (1). EndsWith (Errortype[temp])) {Throw NewIOException (name+ ": Wrong Type"); } } Try{ //Save the uploaded file to the specified directory//when uploading a file to a database later in this article, it will be overwrittenItem.write (NewFile ("d://" + m.group (1))); Out.print (Name+ "+size+" "); } Catch(Exception e) {out.println (e); } } Else { Throw NewIOException ("fail to upload"); } } }} Catch(IOException e) {out.println (e);}Catch(fileuploadexception e) {out.println (e);} }} now describes the upload file to the server, the following only write the relevant code: take SQL2000 as an example, the table structure is as follows: Field name: Name Filecode type: varchar image database Insert code: PreparedStatement pstmt=conn.preparestatement ("INSERT into test values (?,?)"code as follows: ... Try{If this code is not removed, it will be written to the server together//Item.write The new File ("D://"+ m.group (1))); intByteread=0; //read the input stream, that is, the uploaded file contentInputStream instream=Item.getinputstream (); Pstmt.setstring (1,m.group (1)); Pstmt.setbinarystream (2,instream, (int) size); Pstmt.executeupdate (); Instream.close (); OUT.PRINTLN (Name+ "+size+" "); }
Multiple file uploads