Press Ctrl / CMD + C to copy this to your clipboard.
This post will be reported to the moderators as potential spam to be looked at
I am trying to save images that the a member that can upload from the front end as a media node with the Media service
in the view I post to a surface controller
<input asp-for="myfile" type="file"/>
in the post method
if (model.myfile != null)
using (Stream stream = model.myfile.OpenReadStream())
IMedia media = _mediaService.CreateMedia(model.myfile.FileName, -1, Image.ModelTypeAlias);
media.SetValue("umbracoFile",model.myfile); //problem here
//from doc the SetValue method takes a stream
the media.SetValue method takes propertyTypeAlias and object
which is different from the documentation example here
the media node does get created but the images isn't displayed right
any idea would be appreciated
please and thank you
The code in the example is a bit different from yours. Your are, at least, missing the filestream argument, as far as I can see.
The method you are using only sets the value of the "umbracoFile" property on the new media node (which is a string path to the file on the disk). It doesn't actually try to save the file iteself.
You could in theory manually try to save the file to the disk, then get the path of the file and set that as the value for "umbracoFile". But I dont think that is recommended.
There is an extension method that does all the necessary saving of the file creating random path names, setting the path on the media etc. It takes the file as a Stream. Its not very pretty because it takes a bunch of other services as parameters too. So you would need to inject those services and convert your posted file to a stream with something like this:
Inject the following services into your controller:
private readonly MediaFileManager mediaFileManager;
private readonly MediaUrlGeneratorCollection mediaUrlGenerators;
private readonly IShortStringHelper shortStringHelper;
private readonly IContentTypeBaseServiceProvider contentTypeBaseServiceProvider;
Then convert your posted file into a stream and call the extension method something like this (i dont use posted files so this is untested, but it works for me when I get streams from elsewhere)
using (MemoryStream stream = new MemoryStream(model.myfile.FileBytes))
media.SetValue(mediaFileManager, mediaUrlGenerators, shortStringHelper, contentTypeBaseServiceProvider, Constants.Conventions.Media.File, model.myfile.FileName, stream);
Thanks for the great explanation, it worked!
the file is of type IFromFile
so here is what I did, if anyone might be interested
await using (var ms = new MemoryStream())
var media = _mediaService.CreateMedia(model.myfile.FileName, -1, Image.ModelTypeAlias);
media.SetValue(_mediaFileManager, _mediaUrlGeneratorCollection, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, model.myfile.FileName, ms);
is working on a reply...
Write your reply to:
Image will be uploaded when post is submitted