栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

webservice开启MTOM传输大文件详细代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

webservice开启MTOM传输大文件详细代码

题记:主要介绍在spring框架下使用apache CXF框架(JAX-RS),通过MTOM方式进行文件传输,文章结尾会提供批量传输文件思路。

一、服务端代码DEMO 服务端代码包括三部分

1、载体:传输实体,作为远程调用的参数,下面来新建附件POJO实体元数据

package com.pp.typt.ws.fileransport;

import javax.activation.DataHandler;
import javax.xml.bind.annotation.XmlMimeType;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;


@XmlType
public class Attachment {
    private long fileSize;
    private String realName;
    private String filePath;
    private String fileType;

    @XmlMimeType("application/octet-stream")
    private DataHandler attachData;

    public long getFileSize() {
        return fileSize;
    }

    public void setFileSize(long fileSize) {
        this.fileSize = fileSize;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    @XmlTransient
    public DataHandler getAttachData() {
        return attachData;
    }

    public void setAttachData(DataHandler attachData) {
        this.attachData = attachData;
    }
}

2、接口:通过添加注解方式,将服务进行暴露。代码如下,注意代码的注解没有添加属性设置,开发时请根据需要自行添加属性。

package com.pp.typt.ws.fileransport;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import java.io.IOException;

@WebService
public interface AttachmentTransport {
   @WebMethod
   @WebResult
   String transFile(@WebParam(name = "attachment") Attachment attachment) throws IOException;
}

3、实现:接口的业务实现,这里只展示服务端如何从第1的载体中获得完整的输入流,代码如下:

package com.pp.typt.ws.fileransport;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class AttachmentTransportImpl implements AttachmentTransport{
    @Override
    public String transFile(Attachment attachment) throws IOException {
        InputStream inputStream = null ;
        ByteArrayInputStream bInputStream = null;
        long actualFileSize = 0L;
        // 解析数据
        DataHandler inData = attachment.getAttachData();
        DataSource inDataSource = inData.getDataSource();
        long fileSize  = attachment.getFileSize();
        try {
               //获取文件流
                inputStream = inDataSource.getInputStream();

                byte[] bytes = IOUtils.toByteArray(inputStream);
                //拿到文件流全部。
                bInputStream = new ByteArrayInputStream(bytes);

            
        }catch (IOException ioException){
            ioException.printStackTrace();
        }catch (Exception e ){
            e.printStackTrace();
        }finally {
            try {
                 actualFileSize = bInputStream.available();
                System.out.println("finnally文件大小为:"+actualFileSize);
                inputStream.close();
                bInputStream.close();
            }catch (IOException ioException){
                ioException.printStackTrace();
            }
        }
        return "传输的文件大小为:" + actualFileSize+ "字节";
    }
}

二、服务发布

在cxf-servlet.xml 文件中进行如下配置:

    
        
            
        
    
三、客户端代码

服务端开启的MTOM。所以在传输过程中 客户端在根据服务端生成的WSDL文件生成代码后,客户端调用时也需要开启MTOM,以保证文件的稳定传输:客户端代码示例:

package com.pp.typt.ws.fileransport;




import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.util.ByteArrayDataSource;
import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.*;
import javax.xml.ws.soap.SOAPBinding;


public final class AttachmentTransport_AttachmentTransportImplPort_Client {

    private static final QName SERVICE_NAME = new QName("http://fileransport.ws.typt.pp.com/", "AttachmentTransportImplService");

    private AttachmentTransport_AttachmentTransportImplPort_Client() {
    }

    public static void main(String args[]) throws java.lang.Exception {
        URL wsdlURL = AttachmentTransportImplService.WSDL_LOCATION;
        if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
            File wsdlFile = new File(args[0]);
            try {
                if (wsdlFile.exists()) {
                    wsdlURL = wsdlFile.toURI().toURL();
                } else {
                    wsdlURL = new URL(args[0]);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }

        AttachmentTransportImplService ss = new AttachmentTransportImplService(wsdlURL, SERVICE_NAME);
        AttachmentTransport port = ss.getAttachmentTransportImplPort();

        //客户端开启MTOM
        final BindingProvider bp = (BindingProvider) port;
       // bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);
        SOAPBinding binding = (SOAPBinding) bp.getBinding();
        binding.setMTOMEnabled(true);
        {
            System.out.println("Invoking transFile...");
            Attachment _transFile_attachment = new Attachment();
            try {
                //这里读取本地文件流
                _transFile_attachment.setFilePath("LP");
                _transFile_attachment.setFileType("img");
                _transFile_attachment.setRealName("Postman.zip");
                //读取本地文件
                File file = new File("/Desktop/Postman.zip");
                InputStream inputStream = new FileInputStream(file);
                System.out.println("当前文件的大小为:"+inputStream.available());
                _transFile_attachment.setFileSize(inputStream.available());
                //流转为字节数组
                byte[] data = toByteArray(inputStream);
                inputStream.close();
                DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
                DataHandler dataHandler = new DataHandler(dataSource);
                _transFile_attachment.setAttachData(dataHandler);

                //请求并响应,这里响应数据在服务端没有包装。
                java.lang.String _transFile__return = port.transFile(_transFile_attachment);
                System.out.println("transFile.result=" + _transFile__return);

            } catch (Exception e) {
                System.out.println("Expected exception: IOException has occurred.");
                e.printStackTrace();
            }
        }
    }
    //流转字节数组
    private static byte[] toByteArray(InputStream in) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        try {
            while (true) {
                if (!((n = in.read(buffer)) != -1)) break;
                out.write(buffer, 0, n);
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
}

注意如果想实现批量附件传输,则只需要将服务端的入参数设置为 List 类型即可

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677747.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号