一、导入依赖
Jar包方式
com.github.ipfs java-ipfs-api1.3.3 com.github.multiformats java-multihashv1.3.0 com.github.multiformats java-multibasev1.1.0 com.github.multiformats java-multiaddrv1.4.1 com.github.ipld java-cid1.3.3
Maven方式
jitpack.io https://jitpack.io com.github.ipfs java-ipfs-apiv1.3.3
二、代码实例
@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();
}
}
}
}
}
@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);
}
}
青年人的责任重大!努力吧...



