WebService File Upload Download

Source: Internet
Author: User

Use DataHandler to implement WebService file upload and download

Service-Side code:

 PackageCom.hello.weChat.controller;ImportJavax.activation.DataHandler;ImportJavax.activation.FileDataSource;ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;/*** Created by Winkey on 15-2-10.*/ Public classFilecontroller {/** File Upload service*/     Publicstring Upload (DataHandler handler, string fileName) {string FullPath= "F:\\test\\testupload\\" +FileName; File File=NewFile (FullPath); intFlag = 0; if(Handler = =NULL)            return"Failure"; if(FileName = =NULL)            return"Failure"; InputStream input=NULL; FileOutputStream Fos=NULL; Try{input=Handler.getinputstream (); FOS=Newfileoutputstream (file); byte[] buffer =New byte[4096];  while(flag = input.read (buffer))! =-1) {fos.write (buffer,0, flag); }        } Catch(IOException e) {e.printstacktrace (); return"Failure"; } finally {            Try {                if(Input! =NULL) {input.close (); }                if(Fos! =NULL) {fos.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }        return"Success"; }    /** File Download service*/     PublicDataHandler downloadFile () {String filepath= "F:\\test\\head.jpg"; DataHandler DataHandler=NewDataHandler (NewFiledatasource (filepath)); System.out.println ("-------------------------Download"); returnDataHandler; }}

Server-side WSDD file configuration

<service name= "Filecontroller" provider= "Java:rpc" >           <parameter name= "ClassName" value= "Com.hello.weChat.controller.FileController"/>           <parameter name= "Allowedmethods" value= "Downloadfile,upload"/>         <parameter name= "Scope" value= "session"/> <operation name= "upload" qname= "operns:upload" xmlns:operns= "UPL Oad "returntype=" rns:string "xmlns:rns=" Http://www.w3.org/2001/XMLSchema "> <parameter name=" Handler "type = "Ns:datahandler" xmlns:ns= "Http://www.w3.org/2001/XMLSchema"/> <parameter name= "fileName" type= "Ns:strin G "xmlns:ns=" Http://www.w3.org/2001/XMLSchema "/> </operation> <typemapping qname=" Hns:datahandl Er "xmlns:hns=" Ns:filehandler "Languagespecifictype= "Java:javax.activation.DataHandler"Serializer= "Org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory"Deserializer= "Org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory"Encodingstyle= "http://schemas.xmlsoap.org/soap/encoding/"/> </service>

Only configure typemapping when downloading, need to configure both operation and typemaping when uploading

Client:

Download the test class:

 PackageCom.hello.weChat.controller;ImportOrg.apache.axis.client.Call;ImportOrg.apache.axis.client.Service;Importorg.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;Importorg.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;ImportJavax.activation.DataHandler;ImportJavax.xml.namespace.QName;Importjavax.xml.rpc.ServiceException;ImportJava.io.*;Importjava.rmi.RemoteException;/*** Created by Winkey on 15-2-10.*/ Public classDownloadtest { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString url = "Http://192.168.129.245:8080/btm-szny/services/FileController"; Service Service=NewService ();        Call call;        DataHandler handler; InputStream input=NULL; FileOutputStream Fos=NULL; String filepath= "f:/test/"; String filename= filepath + "Tests.jpg"; File File=NewFile (filename); Try{ Call=(call) Service.createcall (); /*** * Register exception class information and serialization classes * xmlns:hns= "in typemapping in Ns:filehandler and WSDD configuration Files" Ns:filehan             Dler "qname= corresponding to Hns:datahandler" DataHandler "in Typemapping in DataHandler and WSDD configuration files * */QName qn=NewQName ("Ns:filehandler", "DataHandler");            Call.settargetendpointaddress (URL); Call.setoperationname (NewQName ("Filecontroller", "DownloadFile")); Call.registertypemapping (DataHandler.class, QN, Jafdatahandlerserializerfactory.class, Jafdatahandlerdeserializerfactory.class);//            //Call.addparameter ("source", xmltype.xsd_string, parametermode.in);//to set the incoming parameter type for a service invocation methodCall.setreturntype (QN, DataHandler.class);//The QName to return and the return type is Datahandler.classHandler = (DataHandler) Call.invoke (Newobject[]{}); Input=Handler.getinputstream (); FOS=Newfileoutputstream (file); byte[] buffer =New byte[1024];  while(Input.read (buffer)! =-1) {fos.write (buffer); }        } Catch(serviceexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(RemoteException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally {            if(Input! =NULL) {                Try{input.close (); } Catch(Exception E2) {//Todo:handle Exception                }            }            if(Fos! =NULL) {                Try{fos.close (); } Catch(Exception E2) {//Todo:handle Exception                }            }        }    }}

Upload Test class:

 PackageCom.hello.weChat.controller;Importjava.rmi.RemoteException;ImportJavax.activation.DataHandler;ImportJavax.activation.FileDataSource;ImportJavax.xml.namespace.QName;ImportJavax.xml.rpc.ParameterMode;Importjavax.xml.rpc.ServiceException;ImportOrg.apache.axis.client.Call;ImportOrg.apache.axis.client.Service;ImportOrg.apache.axis.encoding.XMLType;Importorg.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;Importorg.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;/*** Created by Winkey on 15-2-10.*/ Public classUploadtest { Public Static voidMain (string[] args)throwsserviceexception, remoteexception {String URL= "Http://192.168.129.245:8080/btm-szny/services/FileController"; String FileName= "Head.jpg"; String Path= "f:/test/" +FileName;        SYSTEM.OUT.PRINTLN (path); //this would be equivalent to constructing a file with a path to the files.DataHandler handler =NewDataHandler (NewFiledatasource (path)); Service Service=NewService (); Call Call=(call) Service.createcall ();        Call.settargetendpointaddress (URL); /*** Register exception class information and serialization class Ns:fileuploadhandler and WSDD in the typemapping of xmlns:hns= "Ns:fileuploadhandler" in the configuration file Datahandle DataHandler corresponding to Qname= "Hns:datahandler" in Typemapping in R * and WSDD configuration files*/QName qn=NewQName ("Ns:filehandler", "DataHandler"); Call.registertypemapping (DataHandler.class, QN, jafdatahandlerserializerfactory.class, Jafdatahandlerdeserializerfactory.class); Call.setoperationname (NewQName (URL, "upload")); //To set a method parameter, note that the type of parameter 1 of type DataHandler is the same as that of the qn aboveCall.addparameter ("DataHandler", QN, parametermode.in); Call.addparameter ("FileName", xmltype.xsd_string, parametermode.in); //Set the return value type, the following 2 ways can beCall.setreturnclass (String.class); //Call.setreturntype (xmltype.xsd_string);String Result= (String) Call.invoke (NewObject[] {handler, "remote_server_head.jpg" });    SYSTEM.OUT.PRINTLN (result); }}

WebService File Upload Download

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.