c# - 如何使用 C# 上传文件并将其保存到流中以供进一步预览?

标签 c# asp.net-mvc session file-upload stream

有没有办法上传一个文件,保存到一个Stream中,这个Stream我会暂时保存在一个Session中,最后我会尝试预览这个上传的文件是在这个Session中的吗??

例如pdf文件。

谢谢!!

已编辑

这是我正在尝试做的事情:

HttpPostedFileBase hpf = Request.Files[0] as HttpPostedFileBase;
byte[] buffer = new byte[hpf.InputStream.Length];
MemoryStream ms = new MemoryStream(buffer);
ms.Read(buffer, 0, (int)ms.Length);
Session["pdf"] = ms.ToArray();
ms.Close();

在另一种方法中,我这样做:

byte[] imageByte = null;

imageByte = (byte[])Session["pdf"];

Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Clear();
Response.BinaryWrite(imageByte);

但是什么都没发生...我的浏览器甚至打开了一个 nem 页面来显示 pdf 文件,但是显示了一个窗口说该文件不是 pdf(或者类似的文件不是以 pdf 启动的,我没有明白这一点)

最佳答案

当然是。我将文件(PDF/图像)上传到我的数据库中 app .我的模型对象实际上将文件存储为字节数组,但对于其他功能,我必须在流之间进行转换,因此我确信将其保存为流格式同样容易。

这是我的应用程序中的一些代码示例(复制粘贴)

我用来移动文件(PDF/图像)的 File 对象:

public class File : CustomValidation, IModelBusinessObject
{
    public int ID { get; set; }
    public string MimeType { get; set; }
    public byte[] Data { get; set; }
    public int Length { get; set; }
    public string MD5Hash { get; set; }
    public string UploadFileName { get; set; }
}

..PdfDoc 专门用于 PDF 文件的类型:

public class PdfDoc : File
{
    public int ID { get; set; }
    public int FileID
    {
        get { return base.ID; }
        set { base.ID = value; }
    }
    [StringLength(200, ErrorMessage = "The Link Text must not be longer than 200 characters")]
    public string LinkText { get; set; }


    public PdfDoc() { }

    public PdfDoc(File file)
    {
        MimeType = file.MimeType;
        Data = file.Data;
        Length = file.Length;
        MD5Hash = file.MD5Hash;
        UploadFileName = file.UploadFileName;
    }

    public PdfDoc(File file, string linkText)
    {
        MimeType = file.MimeType;
        Data = file.Data;
        Length = file.Length;
        MD5Hash = file.MD5Hash;
        UploadFileName = file.UploadFileName;

        LinkText = linkText;
    }
}

.. 接收文件上传的多部分 POST 的操作示例:

    //
    // POST: /Announcements/UploadPdfToAnnouncement/ID
    [KsisAuthorize(Roles = "Admin, Announcements")]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult UploadPdfToAnnouncement(int ID)
    {
        FileManagerController.FileUploadResultDTO files =
            FileManagerController.GetFilesFromRequest((HttpContextWrapper)HttpContext);
        if (String.IsNullOrEmpty(files.ErrorMessage) && files.TotalBytes > 0)
        {
            // add SINGLE file to the announcement
            try
            {
                this._svc.AddAnnouncementPdfDoc(
                    this._svc.GetAnnouncementByID(ID),
                    new PdfDoc(files.Files[0]),
                    new User() { UserName = User.Identity.Name });
            }
            catch (ServiceExceptions.KsisServiceException ex)
            {
                // only handle our exceptions
                base.AddErrorMessageLine(ex.Message);
            }
        }

        // redirect back to detail page
        return RedirectToAction("Detail", "Announcements", new { id = ID });
    }

现在您可以看到我在此处将文件对象传递给我的服务,但您可以选择将其添加到 session 并将 ID 传递回“预览” View 等。

最后,这是我用来将文件呈现给客户端的通用操作(您可以使用类似的东西从 session 中呈现文件/流):

    //
    // GET: /FileManager/GetFile/ID
    [OutputCache(Order = 2, Duration = 600, VaryByParam = "ID")]
    public ActionResult GetFile(int ID)
    {
        FileService svc = ObjectFactory.GetInstance<FileService>();

        KsisOnline.Data.File result = svc.GetFileByID(ID);

        return File(result.Data, result.MimeType, result.UploadFileName);
    }

编辑:
我注意到我需要更多样本来解释以上内容-

对于上面的上传操作,FileUploadResultDTO 类:

    public class FileUploadResultDTO
    {
        public List<File> Files { get; set; }
        public Int32 TotalBytes { get; set; }
        public string ErrorMessage { get; set; }
    }

还有 GetFilesFromRequest 函数:

    public static FileUploadResultDTO GetFilesFromRequest(HttpContextWrapper contextWrapper)
    {
        FileUploadResultDTO result = new FileUploadResultDTO();
        result.Files = new List<File>();

        foreach (string file in contextWrapper.Request.Files)
        {
            HttpPostedFileBase hpf = contextWrapper.Request.Files[file] as HttpPostedFileBase;
            if (hpf.ContentLength > 0)
            {
                File tempFile = new File()
                {
                    UploadFileName = Regex.Match(hpf.FileName, @"(/|\\)?(?<fileName>[^(/|\\)]+)$").Groups["fileName"].ToString(),   // to trim off whole path from browsers like IE
                    MimeType = hpf.ContentType,
                    Data = FileService.ReadFully(hpf.InputStream, 0),
                    Length = (int)hpf.InputStream.Length
                };
                result.Files.Add(tempFile);
                result.TotalBytes += tempFile.Length;
            }
        }

        return result;
    }

最后(我希望我现在拥有您需要的一切)这个 ReadFully 函数。这不是我的设计。我从网上得到它 - 流阅读可能很棘手。我发现这个函数是完全读取流的最成功的方法:

    /// <summary>
    /// Reads data from a stream until the end is reached. The
    /// data is returned as a byte array. An IOException is
    /// thrown if any of the underlying IO calls fail.
    /// </summary>
    /// <param name="stream">The stream to read data from</param>
    /// <param name="initialLength">The initial buffer length</param>
    public static byte[] ReadFully(System.IO.Stream stream, long initialLength)
    {
        // reset pointer just in case
        stream.Seek(0, System.IO.SeekOrigin.Begin);

        // If we've been passed an unhelpful initial length, just
        // use 32K.
        if (initialLength < 1)
        {
            initialLength = 32768;
        }

        byte[] buffer = new byte[initialLength];
        int read = 0;

        int chunk;
        while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
        {
            read += chunk;

            // If we've reached the end of our buffer, check to see if there's
            // any more information
            if (read == buffer.Length)
            {
                int nextByte = stream.ReadByte();

                // End of stream? If so, we're done
                if (nextByte == -1)
                {
                    return buffer;
                }

                // Nope. Resize the buffer, put in the byte we've just
                // read, and continue
                byte[] newBuffer = new byte[buffer.Length * 2];
                Array.Copy(buffer, newBuffer, buffer.Length);
                newBuffer[read] = (byte)nextByte;
                buffer = newBuffer;
                read++;
            }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
    }

关于c# - 如何使用 C# 上传文件并将其保存到流中以供进一步预览?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1653469/

相关文章:

c# - 使用 StreamWriter 追加文本

C# 锁定在锁定 block 中重新分配的对象

c# - 如何将 ID 添加到 Html.ActionLink - 与在 HTML/CSS 中一样

android - 将 AudioEffect 附加到全局混音的首选方法?

java - 类型不匹配 : cannot convert from Integer to int

c# - 为什么 C# 内插字符串不接受可变填充?

c# - 模拟C#中同一类中的方法

javascript - jquery和ajax请求

c# - 调用泛型方法并在运行时设置泛型类型

oracle - 如何在PL/SQL包中将 session 变量skip_unusable_indexes设置为true以加速表删除/插入?