commercetools / commercetools-sdk-java-v2

The e-commerce SDK from commercetools for Java.
https://commercetools.github.io/commercetools-sdk-java-v2/javadoc/index.html
Apache License 2.0
35 stars 16 forks source link

How do I upload an image to a product? #161

Closed kzbt closed 3 years ago

kzbt commented 3 years ago

Does the SDK has the equivalent of https://docs.commercetools.com/api/projects/products#upload-a-product-image? I'm trying to upload an image to a variant. The ProductVariantDraft takes an Image object but we first need to upload the image to get the url right? Which api from the sdk can I use to upload the image?

ProductVariantDraft.builder()
    .key(UUID.randomUUID().toString())
    .prices(PriceDraft.builder().value(money).build())
    .images(Image.builder().url("").build())
//                              ^^               
    .attributes(attrs)
    .build();
jenschude commented 3 years ago

The product variant draft expects the URI to a hosted image e.g. from a S3 bucket.

If you want to use the commercetools used CDN you have to use the specific upload endpoint. I just tried it and found out that the image upload endpoint seems to not be correctly working using the SDK. We will fix this with the next release.

jenschude commented 3 years ago

This is a working example:

File imageFile ;
try{
    imageFile = File.createTempFile("ct_logo_farbe",".gif");
    imageFile.deleteOnExit();
    byte[] fileBytes = IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("ct_logo_farbe.gif"));
    FileOutputStream outStream = new FileOutputStream(imageFile);
    outStream.write(fileBytes);
    outStream.close();
}catch(IOException e){
    imageFile = new File("src/test/resources/ct_logo_farbe.gif");
}

final ByProjectKeyRequestBuilder projectRoot = CommercetoolsTestUtils.getProjectRoot();
projectRoot.products().withId(product.getId()).images().post(imageFile).withHeader(ApiHttpHeaders.CONTENT_TYPE, "image/gif").withSku(product.getMasterData().getCurrent().getMasterVariant().getSku()).executeBlocking();

Atm the withVariant is expecting a double value instead of a long. This will be fixed in soon.

jenschude commented 3 years ago

A fix has been released and a test has been added to show the usage:

https://github.com/commercetools/commercetools-sdk-java-v2/blob/0acda3b8c56f5d98c84c123cf95b85fcac16274d/commercetools/commercetools-sdk-java-api/src/integrationTest/java/commercetools/product/ProductIntegrationTests.java#L129-L137