📌  相关文章
📜  下载图像并以编程方式保存到 aem (1)

📅  最后修改于: 2023-12-03 14:48:49.297000             🧑  作者: Mango

如何下载图像并以编程方式保存到 AEM

如果你需要将图像保存到 AEM 中,你可以使用 Java 的 HttpUrlConnection 类来获取指定 URL 上的图像。然后,你可以使用 AEM 提供的 Sling API 将图像保存到 AEM 中。

下面是一个例子,展示了如何下载图像并将其保存到 AEM 中。

import java.io.*;
import java.net.*;
import org.apache.commons.io.IOUtils;
import org.apache.sling.api.resource.*;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageDownloader {
  
  private static final Logger LOGGER = LoggerFactory.getLogger(ImageDownloader.class);

  public void downloadImage(String url, String filename) {
    try {
      URL imageUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
      conn.setDoInput(true);
      conn.connect();
      InputStream inputStream = conn.getInputStream();

      ResourceResolver resourceResolver = getResourceResolver();
      Resource imageResource = resourceResolver.getResource("/content/dam/images/" + filename + ".jpg");
      
      if (imageResource == null) {
        imageResource = resourceResolver.getResource("/content/dam/images");
        imageResource = resourceResolver.create(imageResource, filename + ".jpg", null);
      }

      Node imageNode = imageResource.adaptTo(Node.class);
      Binary binary = createBinary(inputStream);
      imageNode.setProperty("jcr:data", binary);
      resourceResolver.commit();

    } catch (IOException e) {
      LOGGER.error("Could not download image: " + e.getMessage());
    } catch (RepositoryException e) {
      LOGGER.error("Could not save image to AEM: " + e.getMessage());
    }
  }

  private ResourceResolver getResourceResolver() {
    ResourceResolverFactory resourceResolverFactory = sling.getService(ResourceResolverFactory.class);
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put(ResourceResolverFactory.SUBSERVICE, "imageService");
    ResourceResolver resourceResolver = null;
    try {
      resourceResolver = resourceResolverFactory.getServiceResourceResolver(paramMap);
    } catch (org.apache.sling.api.resource.LoginException e) {
      LOGGER.error(e.getMessage());
    }
    return resourceResolver;
  }

  private Binary createBinary(InputStream inputStream) throws RepositoryException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, outputStream);
    ResourceResolver resourceResolver = getResourceResolver();
    ValueFactory valueFactory = resourceResolver.adaptTo(Session.class).getValueFactory();
    return valueFactory.createBinary(new ByteArrayInputStream(outputStream.toByteArray()));
  }
}

这个例子演示了如何将一个图像文件保存到 AEM 中的 /content/dam/images 目录下。

为了执行这个例子,你需要将它放到一个 OSGi Bundle 中,并在 bundle 的 MANIFEST.MF 文件中添加如下依赖:

Require-Capability: osgi.extender;filter:="(osgi.extender=sling.servlet)"
Import-Package: org.apache.sling.api.resource, org.apache.sling.api.request, org.apache.sling.api.response, org.apache.sling.api.servlets, javax.jcr, org.apache.commons.io

在 AEM 中,你需要创建一个新的 Sling Servlet,并在 doGet() 方法中调用 downloadImage() 方法:

import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component(service = Servlet.class, property = {
        "sling.servlet.methods=get",
        "sling.servlet.paths=/bin/image/downloader"
})
public class ImageDownloadServlet extends SlingAllMethodsServlet {

    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        ImageDownloader imageDownloader = new ImageDownloader();
        imageDownloader.downloadImage("http://www.example.com/image.jpg", "my-image");
    }
}

现在,当你访问 http://localhost:4502/bin/image/downloader 时,它会下载图像并保存到 AEM 中。如果你在 /content/dam/images 目录下查看,你应该会看到一个名为 my-image.jpg 的文件。

以上就是如何下载图像并以编程方式保存到 AEM 的示例代码。