1.引入工具依赖:
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version> </dependency>
2.调用接口接收IO流(这里不写入文件到具体路径)
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(你的url);
CloseableHttpResponse httpResponse = httpClient.execute(post);
Header[] headers = httpResponse.getHeaders("Content-Disposition");
byte[] buffer = null;
if (headers.length > 0) {Header header = headers[0];String h = header.toString();String filename = h.substring(h.indexOf("filename=") + 9);URLDecoder.decode(filename, "UTF-8");HttpEntity entity = httpResponse.getEntity();if (null != entity) {InputStream is = entity.getContent();ByteArrayOutputStream fos = new ByteArrayOutputStream ();byte[] b = new byte[2048];int length;while ((length = is.read(b)) > 0) {fos.write(b, 0, length);}is.close();fos.close();buffer = fos.toByteArray();}
}
3.假设pojo类为如下:(此时数据库中字段类型为BLOB)
class file {
private byte[] fileContent;
}
4.最后file.fileContent(buffer),最后执行Mapper等操作。
注意:buffer这个字段,就是为了将输出的内容,以byte[]的形式存起来,然后存入BLOB类型的字段中
如果是新增一条数据,要先insert into file表 (BLOB类型的字段名)value (empty_blob()),
也就是insert多个值的时候,那个字段的值要先insert为empty_blob()
然后更新时,需要传入的类型为byte[]数组(也就是pojo中的字段类型)
ByteArrayOutputStream 这个流 调用 toByteArray() 后即可 转换为 byte[]。