第三方接口文件接收、文件加参数上传服务器、文件字节流上传 byte[]、文件中转功能

注意:idea中字符编码注意改成UTF-8。
注意:win服务器上运行jar包用(管理员CMD)不要用Windows PowerShell
注意:中文乱码可以尝试nohup java -jar -Dfile.encoding=utf-8 admin.jar >> ./register.log 2>&1

  1. 文件接收,转成字节流
public static byte[] downloadFile(String urlString, String appKey) {
        HttpURLConnection connection = null;
        FileOutputStream fileOutputStream = null;
        BufferedInputStream bufferedInputStream = null;
        ByteArrayOutputStream buffer = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type" , "application/json; charset=UTF-8");
            // 添加请求头: appkey
            connection.setRequestProperty("Appkey" , appKey);
            connection.connect();

            // 判断响应代码是否为200(HTTP OK)
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                bufferedInputStream = new BufferedInputStream(connection.getInputStream());
                buffer = new ByteArrayOutputStream();
                byte[] data = new byte[1024];
                int bytesRead;
                while ((bytesRead = bufferedInputStream.read(data)) != -1) {
                    buffer.write(data, 0, bytesRead);
                }
                //转成字节流
                return buffer.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (buffer != null) buffer.close();
                if (bufferedInputStream != null) bufferedInputStream.close();
                if (fileOutputStream != null) fileOutputStream.close();
                if (connection != null) connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

2.文件转发 将字节流文件和参数一起发给第三方接口(注意!必须每个参数都设置ContentType ,否则会乱码)

    public static String doPostFile2(String url, Map<String, String> param, byte[] bytes) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        HttpPost httppost = new HttpPost(url);
        try {
            // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            // 设置请求的编码格式
            builder.setCharset(Consts.UTF_8);
            //注意必须每个参数都设置ContentType ,否则会乱码
            ContentType contentType = ContentType.create("multipart/form-data", Charset.forName("UTF-8"));
            builder.setContentType(contentType);
            // 添加文件,也可以添加字节流
//			builder.addBinaryBody("file", file);
            //或者使用字节流也行,根据具体需要使用
            builder.addBinaryBody("file" , bytes,contentType,param.get("fileName"));
            // 或者builder.addPart("file",new FileBody(file));
            // 添加参数
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addTextBody(key, param.get(key),contentType);
                }
            }
            //httppost.addHeader("token", param.get("token"));
            HttpEntity reqEntity = builder.build();
            httppost.setEntity(reqEntity);
            // 设置超时时间
            httppost.setConfig(getConfig());
            response = httpClient.execute(httppost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }

3.中转代码

  /**
     * 保存文件
     * @param
     * @param
     * @return
     */
    public Boolean saveFile(String doc_id, String fileName, String strType, String PID) throws Exception {
        //接收
        byte[] bytes = HttpUtils.downloadFile("http://xx.xx/?doc_id=" + doc_id, "xxxx");
        Map<String, String> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("fileName",fileName);
        stringObjectHashMap.put("PID",PID);
        stringObjectHashMap.put("strType",strType);
        //发送
        String s = HttpUtils.doPostFile2("http://xx.xx" , stringObjectHashMap, bytes);
        System.err.println("--文件保存返回值--: "+s);
        if(s=="true"||"true".equals(s)){
            return true;
        }else{
            return false;
        }

    }
  1. 接口接收字节流文件和参数,文件下载,文件重名处理
   /**
     * 接收字节流和参数
     */
    @ApiOperation(value = "接收字节流和参数")
    @PostMapping("/addFile")
    public boolean addFile(@RequestParam("fileName")String fileName,@RequestParam("PID")String PID, @RequestParam("strType")String strType, HttpServletRequest request) throws IOException, ServletException {
        //使用request.getPart("file")接收文件流
        Part part = request.getPart("file");
        String submittedFileName = part.getSubmittedFileName();
        System.err.println("submittedFileName: "+submittedFileName);
        String sPath = saveFile(part, PID, strType);
        if(sPath!=null) {
            TblFilepath tblFilepath = new TblFilepath();
            tblFilepath.setItemid(PID);
            tblFilepath.setFileclass(strType);
            if(submittedFileName.contains(".")){
                //split(".")报错要用 split("\\.")
                String[] split = submittedFileName.split("\\.");
                for (String s:split) {
                    System.err.println(s);
                }
                System.err.println();
                tblFilepath.setName(split[0]);
                tblFilepath.setType(split[1]);
            }
            tblFilepath.setFilepath(sPath);
            tblFilepath.setFiletype("基本信息");
            try {
                int i = tblFilepathService.insertTblFilepath(tblFilepath);
                if(i>0){
                    return true;
                }else{
                    return false;
                }
            }catch (Exception e){
                return false;
            }


        }else{
            return false;
        }
    }

    public static  String saveFile(Part filePart,String PID,String strType) throws IOException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 获取文件名
        String fileName = filePart.getSubmittedFileName();
        String fileDbPath = "/shenpi/Project/" + PID;

        String filePath = JnkcyConfig.getProfile() + fileDbPath;

        String frtPath = filePath+"/"+fileName;

        // 根据文件名创建文件用于判断
        File fileToSaveEx = new File(frtPath);
        System.err.println("父目录:"+fileToSaveEx.getParentFile());
        // 保证父目录存在
        if (!fileToSaveEx.getParentFile().exists()) {
            fileToSaveEx.getParentFile().mkdirs();
        }

        File frtFile = new File(frtPath);
        //判断文件是否存在
        if(frtFile.exists()){
            //存在加日期
            frtPath = filePath+"/"+formatter.format(new Date())+fileName;
        }
        File fileToSave = new File(frtPath);
        // 转换成文件
        try (InputStream inputStream = filePart.getInputStream();
             OutputStream outputStream = new FileOutputStream(fileToSave)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return fileDbPath+"/"+fileName;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值