我有一个用 Java 编写的 REST 服务,允许用户上传 jar 文件。用户可以使用类似以下命令上传文件:
curl --request POST --data-binary "@jarToUpload.jar" http://localhost:9090/entry-point/upload
服务将文件作为InputStream
接收。
我需要检索输入并检查 JAR 是否有效。
如果 jar 有效,我需要将其作为流存储在远程主机上。我不需要将其保存在本地。
我已经找到了做到这一点的方法,但它需要创建一个临时文件,验证它然后将其作为流发送到远程。
public static File stream2file(InputStream in) throws IOException {
final File tempFile = File.createTempFile("test", ".jar");
tempFile.deleteOnExit();
try {
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
} catch (Exception e) {
}
return tempFile;
}
File file = stream2file(payload);
ZipFile zip = new ZipFile(file);
boolean hasManifestEntry = zip.getEntry("META-INF/MANIFEST.MF") != null;
if(hasManifestEntry){
FileInputStream fileInputStream = new FileInputStream(file);
}
有没有办法在不保存临时文件的情况下做到这一点?
最佳答案
您可以使用java.util.zip.ZipInputStream动态解析 Zip 文件的类:
public boolean hasManifestEntry(InputStream is) throws IOException {
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if ("META-INF/MANIFEST.MF".equals(entry.getName()))
return true;
}
return false;
}
关于java - 验证 JAR 作为输入流而不保存临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34881127/