Magento – Magento 2 : How to get download link of downloadable product in product detail page

download-linkdownloadablemagento2

I would like to create a download link to the uploaded file on a downloadable product.

All downloadables do not have price and customers do not need to purchase them

Replace Add To Cart button with Download(clicking on download button will download file directly)

Best Answer

On top of the advice provided above, here are 2 approaches to load downloadable files data for a product instance:

1- Using LinkRepositoryInterface

public function __construct(
    \Magento\Downloadable\Api\LinkRepositoryInterface $linkRepository,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->linkRepository = $linkRepository;
    $this->productRepository = $productRepository;
}

public function getLinks($productId) {
    // Load the product from id
    $product = $this->productRepository->getById($productId);

    // Output array
    $output = [];

    // Get the product downloadable links
    $links = $this->linkRepository->getList($product->getSku());

    // Add each link data to the output array
    foreach ($links as $item) {
        $output[] = $item->getData();
    }

    return $output;
}

2- Using directly the product instance

public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->productRepository = $productRepository;
}

public function getLinks($productId) {
    // Load the product from id
    $product = $this->productRepository->getById($productId);

    // Output array
    $output = [];

    // Get the product downloadable links
    $extensionAttributes = $product->getExtensionAttributes();
    $links = $extensionAttributes->getDownloadableProductLinks();

    // Add each link data to the output array
    foreach ($links as $item) {
        $output[] = $item->getData();
    }

    return $output;
}