String TargetUrl ="http://localhost:8080/Test"; Postmethod FilePost=NewPostmethod (TargetUrl) {//This is used in Chinese garbled PublicString Getrequestcharset () {return "UTF-8";// } }; Try{HttpClient Client=NewHttpClient (); File File=NewFile ("c:/News. Xml"); part[] Parts=NewPart[] {NewCustomfilepart (File.getname (), file)}; Filepost.setrequestentity (Newmultipartrequestentity (Parts, Filepost.getparams ())); intStatuscode=Client.executemethod (FilePost); if(StatusCode = =HTTPSTATUS.SC_OK) {System. out. println ("Add File succeeded"); } Else{System. out. println ("failed to add File"); } } Catch(Exception ex) {ex.printstacktrace (); }
import Java.io.File; Import java.io.FileNotFoundException; Import java.io.IOException; Import Java.io.OutputStream; Import Org.apache.commons.httpclient.methods.multipart.FilePart; Import Org.apache.commons.httpclient.util.EncodingUtil; /** * Solve Chinese file name garbled*/ Public classCustomfilepart extends Filepart { PublicCustomfilepart (String filename, file file) throws FileNotFoundException {super (filename, file); } protected voidSenddispositionheader (OutputStream out) throws IOException {Super.senddispositionheader ( out); String filename=GetSource (). GetFileName (); if(FileName! =NULL) { out. Write (Encodingutil.getasciibytes (file_name)); out. Write (quote_bytes); out. Write (encodingutil.getbytes (filename,"Utf-8")); out. Write (quote_bytes); } } }
File tempfile =NewFile (System.getproperty ("Java.io.tmpdir"));//Use System temp file directoryDiskfileitemfactory diskfileitemfactory =Newdiskfileitemfactory (); Diskfileitemfactory.setsizethreshold (4096);//set the buffer size, this is 4KBDiskfileitemfactory.setrepository (Tempfile);//set the buffer directoryServletfileupload fu =Newservletfileupload (diskfileitemfactory); Fu.setsizemax (4194304);//limit file size to 4M MaxList Fileitems =fu.parserequest (Request); Iterator I=Fileitems.iterator (); while(I.hasnext ()) {Fileitem fi=(Fileitem) i.next (); String FileName=Fi.getname (); if(FileName! =NULL) {File fullfile=NewFile (Fi.getname ()); File Savedfile=NewFile (Uploadpath, Fullfile.getname ()); Fi.write (Savedfile); }} System. out. println ("Upload Succeed");
HttpClient Upload file garbled