2

我正在尝试从文件系统中读取图像文件并将其保存为MediaItemUmbraco。

这是我放在一起的代码:

MemoryStream uploadFile = new MemoryStream();
using (FileStream fs = File.OpenRead(tempFilename))
{
    fs.CopyTo(uploadFile);

    HttpPostedFileBase memoryfile = new MemoryFile(uploadFile, mimetype, Path.GetFileName(src.Value));
    IMedia mediaItem = _mediaService.CreateMedia(Path.GetFileName(src.Value), itNewsMediaParent, "Image");
    mediaItem.SetValue("umbracoFile", memoryfile);
    _mediaService.Save(mediaItem);
    src.Value = library.NiceUrl(mediaItem.Id);
}

不幸的是,Umbraco 似乎无法将文件保存在媒体文件夹中。它确实在媒体树中创建了节点,它设置了正确的宽度、高度和其他所有内容。然而它指向/media/1001/my_file_name.jpg. 媒体部分已经包含了几张图片,下一个应该使用的“ID”是“1018”。另外,如果我检查里面/media/1001没有my_file_name.jpg.

我还验证了 memoryfile 的 SaveAs 方法(它是一个 HttpPostedFileBase)永远不会被调用。

谁能帮助我并指出正确的方向来解决这个问题?

4

2 回答 2

3

The Media object reacts differently for some object types pass to it, in the case of files there is an override in the child classes that handles an HTTPPostedFile which is only created during a file post event however the base class HttpPostedFileBase (which is what Umbraco references) can by inherited and implemented so you can pass files to the media service and have Umbraco create the right file path etc.

In the example below I have created a new class called FileImportWrapper that inherits from HttpPostedFilebase I then proceed to override all properties and implement my version of them.

For content type i used the code example presented in this stackoverflow post (File extensions and MIME Types in .NET).

See the example code below.

Class Code

    public sealed class FileImportWrapper : HttpPostedFileBase
    {
        private FileInfo fileInfo;

        public FileImportWrapper(string filePath)
        {
            this.fileInfo = new FileInfo(filePath);
        }

        public override int ContentLength
        {
            get
            {
                return (int)this.fileInfo.Length;
            }
        }

        public override string ContentType
        {
            get
            {
                return MimeExtensionHelper.GetMimeType(this.fileInfo.Name);
            }
        }

        public override string FileName
        {
            get
            {
                return this.fileInfo.FullName;
            }
        }

        public override System.IO.Stream InputStream
        {
            get
            {
                return this.fileInfo.OpenRead();
            }
        }

        public static class MimeExtensionHelper
        {
            static object locker = new object();
            static object mimeMapping;
            static MethodInfo getMimeMappingMethodInfo;

            static MimeExtensionHelper()
            {
                Type mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");
                if (mimeMappingType == null)
                    throw new SystemException("Couldnt find MimeMapping type");
                ConstructorInfo constructorInfo = mimeMappingType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                if (constructorInfo == null)
                    throw new SystemException("Couldnt find default constructor for MimeMapping");
                mimeMapping = constructorInfo.Invoke(null);
                if (mimeMapping == null)
                    throw new SystemException("Couldnt find MimeMapping");
                getMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic);
                if (getMimeMappingMethodInfo == null)
                    throw new SystemException("Couldnt find GetMimeMapping method");
                if (getMimeMappingMethodInfo.ReturnType != typeof(string))
                    throw new SystemException("GetMimeMapping method has invalid return type");
                if (getMimeMappingMethodInfo.GetParameters().Length != 1 && getMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
                    throw new SystemException("GetMimeMapping method has invalid parameters");
            }

            public static string GetMimeType(string filename)
            {
                lock (locker)
                    return (string)getMimeMappingMethodInfo.Invoke(mimeMapping, new object[] { filename });
            }
        }
    }

Usage Code

IMedia media = ApplicationContext.Current.Services.MediaService.CreateMedia("image test 1", -1, Constants.Conventions.MediaTypes.Image);

this.mediaService.Save(media); // called it before so it creates a media id

FileImportWrapper file = new FileImportWrapper(IOHelper.MapPath("~/App_Data/image.png"));

media.SetValue(Constants.Conventions.Media.File, file);

ApplicationContext.Current.Services.MediaService.Save(media);

I hope this helps you and others with the same requirement.

于 2014-02-18T10:21:51.490 回答
3

为了保存媒体,我在 MediaService 中找到了这个方法。但是,我认为可能还有另一种更精致的方法

    [HttpPost]
    public JsonResult Upload(HttpPostedFileBase file)
    {
        IMedia mimage;

        // Create the media item
        mimage = _mediaService.CreateMedia(file.FileName, <parentId>, Constants.Conventions.MediaTypes.Image);
        mimage.SetValue(Constants.Conventions.Media.File, file);
        _mediaService.Save(mimage);  

        return Json(new { success = true});
    }
于 2013-09-26T07:49:22.977 回答