基于HttpClient上传文件客户端及基于SpringBoot服务文件服务端代码编码

1.服务端

@PostMapping("/upload")
    public String updateLoad(@RequestParam("file") MultipartFile... files) {
        List<String> list = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }
                InputStream inputStream = file.getInputStream();
                OutputStream outputStream = new FileOutputStream(String.format("D:\\%s",file.getName()));
                int bytesWritten = 0;
                int byteCount = 0;
                byte[] bytes = new byte[1024];
                while ((byteCount = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, bytesWritten, byteCount);
                    bytesWritten += byteCount;
                }
                inputStream.close();
                outputStream.close();

            }
            return "true";
        } catch (Exception e) {
            return "false";
        }
    }

2. 客户端

2.1 pom.xml

 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.4</version>
</dependency>

2.2 代码

public static void upLoadAttachment(String url, File file) {
        try {
            //转换成文件流
            InputStream is = new FileInputStream(file);
            //创建HttpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            /*
             * 绑定文件参数,传入文件流和contenttype,
             * 此处也可以继续添加其他formdata参数
             */
            builder.addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA, file.getName());
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            //执行提交
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                //将响应的内容转换成字符串
                String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                System.out.println(result);
            }
            if (is != null) {
                is.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
发布了88 篇原创文章 · 获赞 97 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/oYinHeZhiGuang/article/details/104686446