一、导入依赖
Jar包方式
<dependency>
<groupId>com.github.ipfs</groupId>
<artifactId>java-ipfs-api</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>com.github.multiformats</groupId>
<artifactId>java-multihash</artifactId>
<version>v1.3.0</version>
</dependency>
<dependency>
<groupId>com.github.multiformats</groupId>
<artifactId>java-multibase</artifactId>
<version>v1.1.0</version>
</dependency>
<dependency>
<groupId>com.github.multiformats</groupId>
<artifactId>java-multiaddr</artifactId>
<version>v1.4.1</version>
</dependency>
<dependency>
<groupId>com.github.ipld</groupId>
<artifactId>java-cid</artifactId>
<version>1.3.3</version>
</dependency>
Maven方式
<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.3.3</version>
</dependency>
</dependencies>
二、代码实例
@Component
public class IPFSUtil {
public String upload(IPFS ipfs, String fileName) throws IOException {
NamedStreamable.FileWrapper file = new NamedStreamable.FileWrapper(new File(fileName));
MerkleNode addResult = ipfs.add(file).get(0);
return addResult.hash.toString();
}
public String upload(IPFS ipfs, byte[] data) throws IOException {
NamedStreamable.ByteArrayWrapper file = new NamedStreamable.ByteArrayWrapper(data);
MerkleNode addResult = ipfs.add(file).get(0);
return addResult.hash.toString();
}
public byte[] download(IPFS ipfs, String hash) {
byte[] data = null;
try {
data = ipfs.cat(Multihash.fromBase58(hash));
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public void download(IPFS ipfs, String hash, String destFile) {
byte[] data = null;
try {
data = ipfs.cat(Multihash.fromBase58(hash));
} catch (IOException e) {
e.printStackTrace();
}
if (data != null && data.length > 0) {
File file = new File(destFile);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* IPFSTest
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
@Slf4j
public class IPFSTest {
// ipfs的服务器地址和端口
private IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/5001");
@Autowired
private IPFSUtil ipfsUtil;
@Test
public void testIPFSUpload() throws IOException {
// filePath 指的是文件的上传路径+文件名,如D:/1.png
String filePath = "D:\\kyrie.png";
String cid = ipfsUtil.upload(ipfs, filePath);
}
@Test
public void testIPFSDownload() throws IOException {
String cid = "BmxJxgEUoQ7avSXC7BbazTCSqMmySBrIPmSX7ipWCBcLVN1";
String destFile = "D:\\irving.jpg";
ipfsUtil.download(ipfs, cid, destFile);
}
}
青年人的责任重大!努力吧...