1.引入所需要的依赖
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.ipfs</groupId>
<artifactId>java-ipfs-api</artifactId>
<version>v1.2.2</version>
</dependency>
</dependencies>
2.直接上代码
static IPFS ipfs = new IPFS("/ip4/192.168.1.111/tcp/5001");//ipfs的服务器地址和端口
public static String upload(String filePathName) throws IOException {
//filePathName指的是文件的上传路径+文件名,如D:/1.png
NamedStreamable.FileWrapper file = new NamedStreamable.FileWrapper(new File(filePathName));
MerkleNode addResult = ipfs.add(file).get(0);
return addResult.hash.toString();
}
public static void download(String filePathName,String hash) throws IOException {
Multihash filePointer = Multihash.fromBase58(hash);
byte[] data = ipfs.cat(filePointer);
if(data != null){
File file = new File(filePathName);
if(file.exists()){
file.delete();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(data,0,data.length);
fos.flush();
fos.close();
}
}