2014-07-08 208 views
2

我需要幫助,我目前正在開發一個Umbraco api,它將從第三方網站以編程方式創建媒體。Umbraco媒體服務創建媒體

我使用以下命令來創建媒體

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; 
    } 
} 

我在這一行mediaImage.SetValue得到以下錯誤( 「umbracoFile」, 「TEST4」,MS);

<Error> 
    <Message>An error has occurred.</Message> 
    <ExceptionMessage> 
     Length cannot be less than zero. Parameter name: length 
    </ExceptionMessage> 
</Error> 

任何幫助,將不勝感激,

在此先感謝

回答

7

固定的問題。

我需要將文件加載到文件流中,以便我可以訪問該名稱。

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; 
     }