如何将HttpPostedFileBase对象作为文件保存到磁盘

本文关键字:文件 保存 磁盘 HttpPostedFileBase 对象 | 更新日期: 2023-09-27 18:29:44

如何将HttpPostedFileBase对象作为文件保存到磁盘?文件的名称应该是发送到组的警报的id

private static string SaveSharedFile(int userAlertId, HttpPostedFileBase file)
    {
        string fileName = null;
        fileName = System.IO.Path.GetFileName(file.FileName);
        if (fileName != "")
        { 
            BinaryReader br = new BinaryReader(file.InputStream);
            byte[] buffer = br.ReadBytes(file.ContentLength);
            br.Close();
            //Save HttpPostedFileBase object as file at c://Path/Folder should have userAlertId name
        }
        return fileName;
    }

感谢您帮助

如何将HttpPostedFileBase对象作为文件保存到磁盘

如果有可能进行大规模上传,我建议不要使用HttpPostedFileBase.InputStream或File.WriteAllBytes。这两种方法都会将整个上传加载到服务器的内存中,然后再将其交给代码。

更有效的方法是使用System.Web.HttpContext.Current.Request.GetBufferlessInputStream()将文件读取到流中,并根据指定的缓冲区大小写入缓冲区。这还使您可以选择在使用第二个流读取文件时直接将文件写入磁盘,从而最大限度地减少内存使用和时间。

这里有一个例子:

private static string SaveSharedFile(int userAlertId, HttpPostedFileBase file)
    {
        string fileName = null;
        fileName = System.IO.Path.GetFileName(file.FileName);
        if (fileName != "")
        { 
            const int BufferSize = 65536; // 65536 = 64 Kilobytes
            string Filepath = userAlertId.ToString();  
            using (FileStream fs = System.IO.File.Create(Filepath))
            {
                using (Stream reader = System.Web.HttpContext.Current.Request.GetBufferlessInputStream())
                {
                    byte[] buffer = new byte[BufferSize];
                    int read = -1, pos = 0;
                    do
                    {
                        int len = (file.ContentLength < pos + BufferSize ?
                            file.ContentLength - pos :
                            BufferSize);
                        read = reader.Read(buffer, 0, len);
                        fs.Write(buffer, 0, len);
                        pos += read;
                    } while (read > 0);
                }
            }
        }
        return fileName;
    }

编辑:"file"变量仍然用于读取文件等内容。ContentLength,但在我的示例中,GetBufferlessInputStream()只是一个读取帖子的替代位置(假设帖子只是一个文件,文件头可能包含表单值),它允许您选择一次缓冲多少。

如果文件是与表单一起发布的,那么您可能只需要再次将"…GetBufferlessInputStream()"替换为"file.InputStream()"。但是,如果您在读取缓冲区时仍在写入缓冲区,而不是缓冲缓冲区(如您最初的问题中所述),那么它可能仍然足够有效,可以满足您的需求。