改变世界的是这样一群人,他们寻找梦想中的乐园,当他们找不到时,他们亲手创造了它

java文件传输接口

开发的时候碰到这样的需求:需要在一个系统(客户端发送请求)中将文件传输至另外一个系统(服务端接收)中去的实现方式,可以批量传输文件,代码如下:

客户端请求:

    public String upLoadFilePost(String actionUrl, Map<String, File> files) throws IOException {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(5 * 1000);
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post方式
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                + ";boundary=" + BOUNDARY);

        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        // 发送文件数据
        if (files != null)
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                        + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset="
                        + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());
                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }

        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();

        // 得到响应码
        int res = conn.getResponseCode();
        if (res == 200) {
            InputStream in = conn.getInputStream();
            InputStreamReader isReader = new InputStreamReader(in);
            BufferedReader bufReader = new BufferedReader(isReader);
            String line = "";
            String data = "";
            while ((line = bufReader.readLine()) != null) {
                data += line;
            }
            outStream.close();
            conn.disconnect();
            return data;
        }
        outStream.close();
        conn.disconnect();
        return null;
    }

服务端接收接口方法体:

public String fileInteraction(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //操作成功则返回OK
        String result = "";
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; 
        //解析request,将结果放置在list中
        Map<String, List<MultipartFile>> fileMap = multiRequest.getMultiFileMap();
        for (String key : fileMap.keySet()) {
            List<MultipartFile> files = fileMap.get(key);
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    String fileNamePath = file.getOriginalFilename();
                    String[] params = fileNamePath.split("\\.");
                    String filename = "";
                    int i = 0;
                    for (String str : params) {
                        i = i + 1;
                        if (StringUtils.isNotEmpty(filename)) {
                            if (i==params.length) {
                                filename = filename + "." + str;
                            }else{
                                filename = filename + "/" + str;
                            }
                        }else{
                            filename = str;
                        }
                    }
                     // 文件保存路径  
                     String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/wxfile/" + filename;
                     File iFile = new File(filePath);
                     File iFileParent = iFile.getParentFile();
                     if(!iFileParent.exists()){
                         iFileParent.mkdirs();
                     }
                     // 转存文件  
                     file.transferTo(new File(filePath));
                     result = "ok";
                 }
            }
        }
        return result;
    }

调用客户端调用发送请求方法:

     String actionUrl = "http://shuilangyizu.iask.in/liuf/utilController/fileInteraction.do";
        Map<String, File> files = new HashMap<String, File>();
        File file = new File(request.getSession().getServletContext().getRealPath("/") + "upload/temp/1.doc");
        files.put("x."+file.getName(), file);
        File file2 = new File(request.getSession().getServletContext().getRealPath("/") + "upload/temp/1.jpg");
        files.put("y."+file2.getName(), file2);
        String result = utilService.upLoadFilePost(actionUrl, files);

 

posted @ 2018-11-28 11:11  水狼一族  阅读(17938)  评论(4编辑  收藏  举报
改变世界的是这样一群人,他们寻找梦想中的乐园,当他们找不到时,他们亲手创造了它