java byte[]转为文件流并通过http发送到其他服务
java ,http,文件传输
·
背景
公司最近需要把A服务的数据传到B服务,数据中包含图片信息,图片是存在mongoDB,mysql数据库存的是mongoDB的文件id,所以读取图片、文件需要通过文件id查mongoDB,返回的是byte[]。现在需要把byte[]转为文件流传给B服务。
代码实现
A服务
先通过id从mongoDB获取文件字节:
public Optional<FileDocument> getFileById(String id) {
FileDocument fileDocument = mongoTemplate.findById(id, FileDocument.class);
if (fileDocument != null) {
Query gridQuery = new Query().addCriteria(Criteria.where("filename").is(fileDocument.getGridfsId()));
try {
//根据id查询文件
GridFSFile fsFile = gridFsTemplate.findOne(gridQuery);
//打开流下载对象
GridFSDownloadStream in = gridFSBucket.openDownloadStream(fsFile.getObjectId());
if (in.getGridFSFile().getLength() > 0) {
//获取流对象
GridFsResource resource = new GridFsResource(fsFile, in);
//获取数据
fileDocument.setContent(getBytes(resource.getInputStream()));
return Optional.of(fileDocument);
} else {
fileDocument = null;
return Optional.empty();
}`在这里插入代码片`
} catch (IOException ex) {
ex.printStackTrace();
}
}
return Optional.empty();
}
文件对象:FileDocument
@Id // 主键
private String id;
private String name; // 文件名称
private long size; // 文件大小
private Date uploadDate; // 上传时间
private String md5; // 文件MD5值
private byte[] content; // 文件内容
private String contentType; // 文件类型
private String suffix; // 文件后缀名
private String description; // 文件描述
发送http请求:
```java
public static String httpFilePost(byte[] bytes, String fileName,String url,long size) {
DataOutputStream out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL console = new URL(url);
HttpURLConnection conn = (HttpURLConnection) console.openConnection();
conn.addRequestProperty("fileName", new String(fileName.getBytes("GBK")));
conn.addRequestProperty("fileSize", String.valueOf(size));
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
out.write(bytes);
out.flush();
out.close();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
conn.disconnect();
} catch (Exception e) {
log.error("Upload failed: {}", e);
} finally {
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
log.error("调用in.close Exception, url=" + url + ",param=" + fileName, ex);
}
}
return result.toString();
}
参数为文件对象的属性,到此A服务代码结束。
B服务
/**
*
* 接收文件信息
* @param request
* @return
*/
@ResponseBody
@RequestMapping("/receiveFile")
public Json receiveFile(HttpServletRequest request) {
Json json = new Json();
try {
String fileName = new String(request.getHeader("fileName").getBytes("GBK"));
String fileSize = new String(request.getHeader("fileSize").getBytes("GBK"));
ServletInputStream in = request.getInputStream();
byte[] bytes = IOUtils.toByteArray(in);
UploadFile uploadFile = new UploadFile();
uploadFile.setId(UUID.randomUUID().toString().replaceAll("-",""));
uploadFile.setName(fileName);
uploadFile.setCreateTime(new Date());
uploadFile.setContent(new Binary(bytes));
//uploadFile.setContentType(file.getContentType());
uploadFile.setSize(Long.valueOf(fileSize));
//存mongoDb ,到此文件就从A服务传到B服务了。
mongoTemplate.save(uploadFile, Constants.MONGDB_IMAGE_FHXC);
json.setObj(uploadFile.getId());
json.setSuccess(true);
}catch (Exception e){
e.printStackTrace();
}
return json;
}
备注:1、如果文件是存在磁盘或者云存储(阿里云、七牛云等),都是先把文件读到再进行操作。
2、如果是在页面上传文件后就同步的话,可以参考其他文献。
参考文献:https://blog.csdn.net/MachineRandy/article/details/112490604
更多推荐
已为社区贡献1条内容
所有评论(0)