MVC 3 не может получить потоковые изображения для показа в Internet Explorer или Chrome - PullRequest
1 голос
/ 01 февраля 2012

У меня возникли некоторые проблемы с отображением потоковых изображений в Internet Explorer или Google Chrome, но в Firefox они выглядят нормально. Я вставил свой код ниже, я собрал его, используя множество битов и бобов, которые я нашел в Google.

public ImageResult GetPhotoS(string photoID, int userID, int? galleryID)
    {
        if (galleryID == null)
        {
            string thumbLocation = string.Format("{0}{1}\\Pics\\{2}_thumb.jpg", ConfigurationManager.AppSettings["PhotoLocation"].ToString(), Convert.ToInt32(User.Identity.Name), photoID);

            using (FileStream stream = new FileStream(thumbLocation, FileMode.Open))
            {
                FileStreamResult fsResult = new FileStreamResult(stream, "image/jpeg");
                ImageResult result = new ImageResult(ReadFully(fsResult.FileStream), "image/jpeg");

                return result;
            }
        }
    }

private static byte[] ReadFully(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

public class ImageResult : ActionResult
{
    public String ContentType { get; set; }
    public byte[] ImageBytes { get; set; }
    public String SourceFilename { get; set; }

    //This is used for times where you have a physical location
    public ImageResult(String sourceFilename, String contentType)
    {
        SourceFilename = sourceFilename;
        ContentType = contentType;
    }

    //This is used for when you have the actual image in byte form
    //  which is more important for this post.
    public ImageResult(byte[] sourceStream, String contentType)
    {
        ImageBytes = sourceStream;
        ContentType = contentType;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.Clear();
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.ContentType = ContentType;

        //Check to see if this is done from bytes or physical location
        //  If you're really paranoid you could set a true/false flag in
        //  the constructor.
        if (ImageBytes != null)
        {
            var stream = new MemoryStream(ImageBytes);
            stream.WriteTo(response.OutputStream);
            stream.Dispose();
        }
        else
        {
            response.TransmitFile(SourceFilename);
        }
    }
}

Я отображаю изображения, используя следующее:

<img src="@Url.Action("GetPhotoS", "Image", new { photoID = photo.ID, userID = Convert.ToInt32(User.Identity.Name) })" alt="@photo.Description" />

Все, что я получаю от Chrome и IE, это обычные красные кресты, где должно быть изображение. Любая помощь будет оценена.

1 Ответ

0 голосов
/ 16 февраля 2012

Вы пытались вернуть FileContentResult?

public FileContentResult GetPhotoS(string photoID, int userID, int? galleryID)
    {
        if (galleryID == null)
        {
            string thumbLocation = string.Format("{0}{1}\\Pics\\{2}_thumb.jpg", ConfigurationManager.AppSettings["PhotoLocation"].ToString(), Convert.ToInt32(User.Identity.Name), photoID);

            using (FileStream stream = new FileStream(thumbLocation, FileMode.Open))
            {
                return File(ReadFully(stream), "image/jpeg");
            }
        }

        throw new FileNotFoundException("Could not find gallery");
    }

Это также кажется немного избыточным, почему бы просто не объединить URL с использованием photoId, userId и galleryId?Изображения хранятся вне webroot?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...