Sap Hybris Tip 3 – Customize The Media Urls
In this post, we will learn about how to custom the media url as our expected.
As usual, we upload a media file, the media URL will contain some text like “..?context=…”, if we share this URL and after a period of time, we can not access that URL anymore because the new version is updated, and it annoyance us frequently.
So, we would like to generate the URL as our expected like: /media/science-pdf/computer-science.pdf
So, let’s go.
Step 1: Create a folder to contain file
We can create the media folder in BO or impex. Example: the media folder name is science-pdf.
Step 2: Add configuration for your URL Custom strategy.
In the project.properties file, we add the following configurations:
media.folder.science.url.strategy=staticMediaURLStrategy
Step 3: Create StaticMediaURLStrategy class which implement MediaURLStrategy from OOTB and override the getUrlForMedia method.
public class StaticMediaURLStrategy implements MediaURLStrategy
{
private static final String MEDIA = "media";
private static final String MIME_TYPE_PDF = "application/pdf";
private static final String SCIENCE_PDF_FOLDER = "science-pdf";
private static final String BACKSLASH = "/";
@Resource(name = "modelService")
private ModelService modelService;
@Override
public String getUrlForMedia(MediaStorageConfigService.MediaFolderConfig config, MediaSource mediaSource) {
// mediaSource.getMime() - application/pdf
MediaModel mediaModel = modelService.get(PK.fromLong(mediaSource.getMediaPk()));
if(null != mediaModel && MIME_TYPE_PDF.equalsIgnoreCase(mediaModel.getMime())
&& StringUtils.equalsAnyIgnoreCase(config.getFolderQualifier(), SCIENCE_PDF_FOLDER)){
String mediaCode = mediaModel.getCode();
return BACKSLASH + MEDIA + BACKSLASH + mediaModel.getCode();
}
return StringUtils.EMPTY;
}
}
References: https://answers.sap.com/questions/12759685/question-on-how-to-customize-media-url-generation.html
Happy Coding.!!! <3