分享知识 传递快乐

在 SpringBoot 下通过把取到的 byte[] 字节文件上传到服务器。实现如下:

byte[]流上传服务

import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;


public class UploadUtils {

private String upload(byte[] bytes, String fileName) {
try {
// 数组转输入流
InputStream inputStream = new ByteArrayInputStream(bytes);
// 输入流转MultipartFile对象
MultipartFile multipartFile = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
// 把MultipartFile这个对象转成输入流资源(InputStreamResource)
InputStreamResource isr = new InputStreamResource(multipartFile.getInputStream(), fileName);
log.info("upload file name : " + fileName);

Map<String, Object> map = new HashMap<>();
map.put("file", isr);

HttpResponse execute = HttpRequest.post("url")
.contentType("multipart/form-data")
.form(map)
.execute();

if (execute.getStatus() == 200) {
JSONObject jsonObject = JSONUtil.parseObj(execute.body());
if (jsonObject.getInt("errcode") == 200 && jsonObject.getJSONObject("datas") != null) {
return jsonObject.getJSONObject("datas").getStr("url");
}
}
} catch (Exception e) {
log.error("上传文件失败", e);
}
return null;
}

}

服务器接收

controller

@PostMapping("/upload/{appName}")
public Result upload(String appName, MultipartFile file) {

return minIoBiz.upload(appName, file);
}

—————————
如有不足请留言指正
相互学习,共同进步