Reputation: 111
I need help, I am currently developing an Umbraco api which will create media programatically from a 3rd party website.
I am using the following to create the media
public HttpResponseMessage CreateMedia()
{
var mediaService = Services.MediaService;
using (WebClient client = new WebClient())
{
Stream s = client.OpenRead("http://karl.media.local/Uploads/ef093845-41dd-4620- b220-1b346a5f9b2e.jpg");
using (MemoryStream ms = new MemoryStream())
{
s.CopyTo(ms);
var mediaImage = mediaService.CreateMedia("test4", 1152, "Image");
mediaImage.SetValue("umbracoFile", "test4", ms);
mediaService.Save(mediaImage);
}
}
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("ExternalMediaCreate", Encoding.UTF8, "application/json");
return response;
}
}
I am getting the following error on this line mediaImage.SetValue("umbracoFile", "test4", ms);:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Length cannot be less than zero. Parameter name: length
</ExceptionMessage>
</Error>
Any help would be appreciated,
Thanks in advance
Upvotes: 3
Views: 5090
Reputation: 111
Fixed, the issue.
I needed to load the file into a filestream so I could access the name.
public HttpResponseMessage CreateMedia()
{
var mediaService = Services.MediaService;
var request = WebRequest.Create("http://karl.media.local/Uploads/ef093845-41dd-4620-b220-1b346a5f9b2e.jpg");
var webResponse = request.GetResponse();
var responseStream = webResponse.GetResponseStream();
if (responseStream != null)
{
var originalImage = new Bitmap(responseStream);
var path = HttpContext.Current.Server.MapPath("~/_tmp/ef093845-41dd-4620-b220-1b346a5f9b2e.jpg");
originalImage.Save(path, ImageFormat.Jpeg);
FileStream fileStream = new FileStream(path, FileMode.Open);
var test = fileStream.Name;
var mediaImage = mediaService.CreateMedia("test4", 1152, "Image");
mediaImage.SetValue("umbracoFile", test, fileStream);
mediaService.Save(mediaImage);
responseStream.Dispose();
webResponse.Dispose();
originalImage.Dispose();
}
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("ExternalMediaCreate", Encoding.UTF8, "application/json");
return response;
}
Upvotes: 8