Restful接口上传word .doc .docx文件流总结

版权声明:该文章为博主原创,转载请告知 https://blog.csdn.net/hanzl1/article/details/81216972

1.文档的几种类型  使用notpad++打开

1). .doc   xml格式的,这种文件比较好传 

2).docx  二进制的显示

3).doc

综上就遇到这几种内容类型的doc和docx

2.坑:我网上百度了好些方法都是这样 (注意代码红色部分)

都是类似如下代码  红色部分 加boundary   加twoHyphens  加 --写入到流里面,这样传输流的过程中解决了 报500的问题,

但是文件下载的时候,这些标记符也在。我试了在服务端读取文件为文本 再替换 文本中的标志符,发现总是可能丢失数据,

下载下来的word还是打不开。提示数据错误。

public class HttpConnectionUtil {


    /**
     * 多文件上传的方法
     * 
     * @param actionUrl:上传的路径
     * @param uploadFilePaths:需要上传的文件路径,数组
     * @return
     */
    @SuppressWarnings("finally")
    public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        DataOutputStream ds = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            // 统一资源
            URL url = new URL(actionUrl);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码连接参数
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            
            
            httpURLConnection.setRequestProperty("bus-type", "02");//接口请求类别编码。01: 发送报表数据
            String filename2=java.net.URLEncoder.encode("政府财务报告sss.doc", "UTF-8");
            httpURLConnection.setRequestProperty("filename", filename2);
            httpURLConnection.setRequestProperty("gcfr-type", "2"); //财报数据类型。1:部门财务报表 2:综合财务报表
        /*    urlConnection.setRequestProperty("rpt-code", "2019");//报表编码。“1”开头的报表属于部门财务报表的编码。“2”开头的报表属于综合财务报表的编码。
*/            httpURLConnection.setRequestProperty("AdmDivGuid", "49EE8B9DD42E4628A5B24EBE86EC2A26");//区划唯一32位标识
            httpURLConnection.setRequestProperty("AdmDivCode", "1100");//区划编码,例如:3100(上海市)
            httpURLConnection.setRequestProperty("AgencyGuid", "49EE8B9DD42E4628A5B24EBE86EC2A26");//区划唯一32位标识
            httpURLConnection.setRequestProperty("AgencyCode", "1100");//区划编码,例如:3100(上海市)
            httpURLConnection.setRequestProperty("year", "2016");
            httpURLConnection.setRequestProperty("username", "110hz");
            httpURLConnection.setRequestProperty("password", "123");
            httpURLConnection.setRequestProperty("checkcode", "?");

            // 设置DataOutputStream
            ds = new DataOutputStream(httpURLConnection.getOutputStream());
            for (int i = 0; i < uploadFilePaths.length; i++) {
                String uploadFile = uploadFilePaths[i];
                String filename = uploadFile.substring(uploadFile.lastIndexOf("\\\\") + 1);
                ds.writeBytes(twoHyphens + boundary + end);
                ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
                        + "\"" + end);
                ds.writeBytes(end);
                FileInputStream fStream = new FileInputStream(uploadFile);
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length = -1;
                while ((length = fStream.read(buffer)) != -1) {
                    ds.write(buffer, 0, length);
                }
                ds.writeBytes(end);
                /* close streams */
                fStream.close();

            }
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            ds.flush();
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                tempLine = null;
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (ds != null) {
                try {
                    ds.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            return resultBuffer.toString();
        }
    }

}

可能别人会有后续的处理吧,但是跟我这需求不一样,我这是要求数据就是以流的形式传输,数据不能有问题,否则下载的时候打不开。

3.解决方式   

思路是base64转码word数据,到服务端解码

客户端代码 调用顺序  

3.1.service调用

String uploadfilepath []=new String[] { "E:\\test\\22.doc" };
            String  actionurl="http://127.0.0.1:7001/abc/service";
        
            if(bus_type.equals("02")){
                String result=HttpConnectionUtil.uploadFile(actionurl,uploadfilepath , 
                        filename2, gcfr_type, admdivguid, admdivcode, 
                        admdivguid, admdivcode, year, username, password, checkcode);
                return result;
            }

3.2.HttpConnectionUtil.java  处理   粘贴HttpConnectionUtil.java 两个方法uploadFile 代码和 readdocOrdocx

 public static String uploadFile(String actionUrl, String[] uploadFilePaths,String filename2,
        String gcfr_type, String AdmDivGuid,String AdmDivCode,String AgencyGuid,String AgencyCode,String year,String username,
        String password,String checkcode) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        DataOutputStream ds = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            // 统一资源
            URL url = new URL(actionUrl);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码连接参数
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
           
          
            httpURLConnection.setRequestProperty("bus-type", "02");//接口请求类别编码。01: 发送报表数据
            //String filename2=java.net.URLEncoder.encode("政府财务报告sss.doc", "UTF-8");
            httpURLConnection.setRequestProperty("filename", filename2);
            httpURLConnection.setRequestProperty("gcfr-type", gcfr_type); //财报数据类型。1:部门财务报表 2:综合财务报表
        /*    urlConnection.setRequestProperty("rpt-code", "2019");//报表编码。“1”开头的报表属于部门财务报表的编码。“2”开头的报表属于综合财务报表的编码。
*/            httpURLConnection.setRequestProperty("AdmDivGuid",AdmDivGuid);//区划唯一32位标识
            httpURLConnection.setRequestProperty("AdmDivCode", AdmDivCode);//区划编码,例如:3100(上海市)
            httpURLConnection.setRequestProperty("AgencyGuid", AgencyGuid);//区划唯一32位标识
            httpURLConnection.setRequestProperty("AgencyCode", AgencyCode);//区划编码,例如:3100(上海市)
            httpURLConnection.setRequestProperty("year", year);
            httpURLConnection.setRequestProperty("username", username);
            httpURLConnection.setRequestProperty("password", password);
            httpURLConnection.setRequestProperty("checkcode", checkcode);
           
            // 设置DataOutputStream
            ds = new DataOutputStream(httpURLConnection.getOutputStream());
            for (int i = 0; i < uploadFilePaths.length; i++) {
                String uploadFile = uploadFilePaths[i];
                String filename = uploadFile.substring(uploadFile.lastIndexOf("\\\\") + 1);
                readdocOrdocx(filename,ds,end,uploadFile);
            }
            //ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            ds.flush();
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                tempLine = null;
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (ds != null) {
                try {
                    ds.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            return resultBuffer.toString();
        }
    }

/***
     *
     * @throws Exception 
     */
    public static void readdocOrdocx(String filename,DataOutputStream ds,String end,String filePath) throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        /*
         String name="ceshi.doc";
        if(filename.lastIndexOf("docx")>0){
           ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\"" + name
               + "\"" + end);
       }
           ds.writeBytes("");
           if(filename.lastIndexOf("docx")>0){
           ds.writeBytes(end);
           }*/
           FileInputStream fStream = new FileInputStream(filePath);
           int bufferSize = 1024;
           byte[] buffer = new byte[bufferSize];
           int length = -1;
           while ((length = fStream.read(buffer)) != -1) {
               baos.write(buffer, 0, length);
           }
           byte[] filebyte=baos.toByteArray();
           //加密
           String enfileStr=StringUtil.encryptBASE64(filebyte);//加密后密文
           ds.writeBytes(enfileStr);
           /*if(filename.lastIndexOf("docx")>0){
           ds.writeBytes("--");
           ds.writeBytes(end);
          }*/
           /* close streams */
           fStream.close();
    }

3.3StringUtil.java 代码

package gov.mof.fasp2.gcfr.inter_test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.output.ByteArrayOutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/****
 * 
 * @author hanzl
 *  Base64加密解密类
 */
public class StringUtil {
    
    public static void main(String args[]) throws Exception{
        
        String a="hanzl";
        //加密
        String b=encryptBASE64(a.getBytes());
        System.out.println(b);
        //解密
        byte[] c=decryptBASE64(b);
        String d=new String(c);
        System.out.println(d);
        
    }

     /***
     * BASE64 解密
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {  
        return (new BASE64Decoder()).decodeBuffer(key);  
    }  
       
    /** 
     * BASE64加密 
     *  
     * @param key 
     * @return 
     * @throws Exception 
     */  
    public static String encryptBASE64(byte[] key) throws Exception {  
        return (new BASE64Encoder()).encodeBuffer(key);  
    }  
   /**
    * 通过路径读取文件内容为字符串
    * @param path
    * @return
 * @throws UnsupportedEncodingException 
    */
    public static String getStringByFilePath(String path) throws UnsupportedEncodingException {
        String xmlString;
        byte[] strBuffer = null;
        int flen = 0;
        File xmlfile = new File(path);
        try {
        InputStream in = new FileInputStream(xmlfile);
        //flen = (int)xmlfile.length();
        //System.out.println("xmlfile长度:"+flen);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];  
        int len;  
        while((len=in.read(buffer))>-1){
            byteStream.write(buffer, 0, len);
        }
        strBuffer=byteStream.toByteArray();
        //strBuffer = new byte[flen];
        //in.read(strBuffer, 0, flen);
        } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        xmlString = new String(strBuffer); //构建String时,可用byte[]类型,
       
        return xmlString;
        }
}
4.服务端解码

    ServletInputStream in = request.getInputStream();
            
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];  
            int len;  
            while((len=in.read(buffer))>-1){
                byteStream.write(buffer, 0, len);
            }
            System.out.println(byteStream.toString());
            byte[] buf=byteStream.toByteArray();
            
            /**解密*/
            String enfileStr=new String(buf); //加密后数据
            
            byte[] newbuf=StringUtil.decryptBASE64(enfileStr);//解密

猜你喜欢

转载自blog.csdn.net/hanzl1/article/details/81216972