Umbraco媒体服务创建媒体

时间:2014-07-08 13:30:04

标签: c# umbraco asp.net-web-api

我需要帮助,我目前正在开发一个Umbraco api,它将以编程方式从第三方网站创建媒体。

我使用以下内容创建媒体

    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>

任何帮助将不胜感激,

提前致谢

1 个答案:

答案 0 :(得分:8)

修正了问题。

我需要将文件加载到文件流中,以便我可以访问该名称。

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