HttpClient由Client客户端上传File文件流至Server服务端

时间:2022-03-05 13:06:04

客户端方法

 public static void main(String[] args) {
        File file=new File("E:\\lucene\\rev\\全年平台受理量.docx");
        postFile(file);
    }
    
    /**
     * 将文件提交至文件服务器
     * @param file 文件对象
     * @return FileStatus 上传结果
     */
    public static String postFile(File file) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = null;
        try {
            //服务器地址
            HttpPost httpPost = new HttpPost("http://192.168.xx.xx:8080/xxxx");
            MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532 );
            mEntityBuilder.addBinaryBody("file", file);
            httpPost.setEntity(mEntityBuilder.build());
            response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                result =EntityUtils.toString(resEntity);
                // 消耗掉response
                EntityUtils.consume(resEntity);
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpclient);
            HttpClientUtils.closeQuietly(response);
        }
        return result;
    }

服务器方法

/**
     * 上传文件
     * @param fileRequest
     * @throws IOException 
     * @throws IllegalStateException 
     */
    @RequestMapping("/postFile.jzse")
    public void postFile(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
        String result = "error";
        Map<String, Object> map = new HashMap<String, Object>();
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request
            .getSession().getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 取得上传文件
                MultipartFile multipartFile = multiRequest.getFile(iter.next());
                if (null != multipartFile) {
                    // 取得当前上传文件的文件名称
                    String fileName = multipartFile.getOriginalFilename();
                    if (fileName.trim() != null && fileName.trim().length() > 0) {
                        CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
                        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
                        File tempFile = fi.getStoreLocation();
                        // 拿到文件,存储
                        multipartFile.transferTo(new File("E:\\lucene\\upload\\"+multipartFile.getOriginalFilename()));
                        result = "success";
                    }
                }
            }
        }
    }

  

httpclient的jar包

httpclient-4.5.2.jar

httpmime-4.2.3.jar

   

注意:上传文件出现乱码

MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);

// multipartEntityBuilder.setCharset(Charset.forName(HTTP.UTF_8));

//设置请求的编码格式,填坑,遇到乱码时,第一错觉就是设置请求的编码格式,如果设置这个编码,会导致多文件丢失(具体原因不明)

 // multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

//设置浏览器兼容模式 ,填坑,网上好多文章说,设置成BOWSER_COMPATIBLE 就不会乱码了,问题就出现在这里,设置模式时,应该设置成HttpMultipartMode.RFC6532 才没有出现乱码



作者:fumingjiang
链接:https://www.jianshu.com/p/fa96d165c51e
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。