java實現ipfs檔案的上傳和下載
阿新 • • 發佈:2018-12-16
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(); } }