Export "File" field to media library

Johnny Nguyen asked on March 7, 2018 05:02

Hi,

I have a custom page type with an image field with data type is "File". I realized that is not a good solution because image URLs will be "~/getattachment/guid/file name" and it isn't good for SEO. Therefore, I would like to change its data type to "Text" and form control will be "Media selection".

When changing the data type, I don't want to re-input the images, so I tried to use API to get uploaded images to the "File" field and upload to Media Library. I can retrieve attachment information (file name, extension, file size, etc.) using DocumentHelper class, but file binary. var ai = DocumentHelper.GetAttachment(attachmentGuid, SiteContext.CurrentSiteName, true);

My question is:
1. Is there any officially way to export image from the "File" field and upload to media library?
2. Could I get the uploaded file binary programmatic except download it from URL "~/getattachment/guid/file name"?

Correct Answer

Trevor Fayas answered on March 7, 2018 14:25

What I would do is first create another field that will house the proper url, then use the webclient.downloadfile(url, pathplusfilename) to download the file from the getattachment info (use the attachment guid and file name to generate the /getattachment url path). Put these files in a temporary folder first, then use the media library API to place them in the media library.

Lastly take the new media library file and build it's url to place in the new field you created.

Once you've done this all, you can delete the existing file field and rename the new text field.

If you need code help just tell me, but check first Kentico API samples.

1 votesVote for this answer Unmark Correct answer

Recent Answers


Peter Mogilnitski answered on March 7, 2018 15:23 (last edited on March 7, 2018 15:33)

There is no official way. You have to write a piece of code using API and convert attachment to media library pretty much what Trevor said above. It also depends on your system setup i.e. setting->system->files->storage. Most likely your attachments are stored as binaries in the DB. If they were files the conversion would been easier. You can use API to work with attachments and check AttachmentInfo members .

1 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.