需求是对接第三方接口,需要将第三方上传的文件保存到数据库中,所以想到了用此方法。
具体的代码如下:
public class AttachmentUtil {
public static MultipartFile urlToMultipartFile(String fulUrl,String name) throws Exception {
try {
// 将在线地址转换为URL对象
URL url = new URL(fulUrl);
// 打开URL连接
URLConnection connection = url.openConnection();
// 转换为HttpURLConnection对象
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
// 获取输入流
InputStream inputStream = httpURLConnection.getInputStream();
// 读取输入流中的数据,并保存到字节数组中
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
// 转换为字节数组
byte[] bytes = byteArrayOutputStream.toByteArray();
// 创建MultipartFile对象
IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
return new CommonsMultipartFile(fileItem);
}catch (IOException ex){
throw new BusinessServiceException(ExceptionEnum.AuthException01.getCode(), "获取附件信息失败");
}
}
}