使用java中的http客户端将字节数组作为文件发送 [英] Send Byte array as file in using http client in java

查看:667
本文介绍了使用java中的http客户端将字节数组作为文件发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有文件的字节数组,我们想将其作为文件上传。
FileBody 仅获取 File 作为参数,但我们有一个字节数组。

We have byte array of file and we want to upload it as file. FileBody only gets File as parameter but we have a array of bytes.

一种解决方案是将字节数组保存到文件中,然后将其发送给
,但这对我来说不合适。

One solution is to save byte array into file and then send it but it is not appropriate for me.

byte b[]= new byte[1000];
//fill b
MultipartEntity form = new MultipartEntity();
form.addPart("file", new FileBody(/* b? */));

谢谢。

推荐答案

您可以执行以下操作

HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new InputStreamBody(new ByteArrayInputStream(b), "my-file.txt");
form.addPart("file", cd);

HttpEntityEnclosingRequestBase post = new HttpPost("");//If a PUT request then `new HttpPut("");`
post.setEntity(form);
client.execute(post);

这篇关于使用java中的http客户端将字节数组作为文件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆