【问题标题】:ASP.NET - Using Session to store FileUpload object [duplicate]ASP.NET - 使用 Session 存储 FileUpload 对象
【发布时间】:2017-02-26 11:25:02
【问题描述】:

我想在Session 中存储一个包含图像的FileUpload 对象。然后在下一页上,我想将图像保存到一个文件夹中。我可以毫无问题地做到这一点,但是当我尝试存储更大的图像时,图像变为 0kb 并且 Windows 照片查看器说文件是空的。这是我的代码:

上传表单页面 (C#):

//FileUploadPicture is of type FileUpload
Session["fileupload_object"] = FileUploadPicture;

将图片保存到文件夹页面 (C#):

Boolean imageUploadStatus = false;
string imageExtension = System.IO.Path.
    GetExtension(((FileUpload)Session["fileupload_object"]).FileName);
string[] acceptedImageExtensions = { ".gif", ".png", ".jpg", ".jpeg" };

for (int i = 0; i < acceptedImageExtensions.Length; i++)
{
    if (imageExtension.Equals(acceptedImageExtensions[i],
        StringComparison.InvariantCultureIgnoreCase))
        {
            imageUploadStatus = true;
        }
}

try
{

((FileUpload)Session["fileupload_object"]).PostedFile.
    SaveAs(imagePath + ((FileUpload)Session["fileupload_object"]).FileName);

}

catch (Exception ex) { }

这里是上传图片的截图。

小图上传就好了:

Small images uploaded without failure

略大的图片上传失败:

744kB image turns 0kB after uploaded

那么,我该如何解决这个问题呢?提前致谢。

更新代码:

上传表单页面 (C#):

Session["fileupload_filename"] = FileUploadPictureOfPaymentStatement.FileName;
HttpPostedFile httpPostedFile = FileUploadPictureOfPaymentStatement.PostedFile;
System.Drawing.Image image = Bitmap.FromStream(httpPostedFile.InputStream);
Session["image"] = image;

将图片保存到文件夹页面 (C#):

Boolean imageUploadStatus = false;
string imageExtension = System.IO.Path.GetExtension((Session["fileupload_filename"])
    .ToString());
string[] acceptedImageExtensions = { ".gif", ".png", ".jpg", ".jpeg" };
for (int i = 0; i < acceptedImageExtensions.Length; i++)
{
    if (imageExtension.Equals(acceptedImageExtensions[i], 
        StringComparison.InvariantCultureIgnoreCase))
    {
        imageUploadStatus = true;
    }
}

if(imageUploadStatus)
{
    try
    {
        ((System.Drawing.Image)Session["image"])
            .Save(imagePath + Session["fileupload_filename"].ToString());
    } catch(Exception ex) { }
}

【问题讨论】:

  • 嗨,你试过this吗?
  • 如果你真的,真的,必须将它存储在会话中,不要存储实际的 fileUploadControl - 保存文件数据本身。
  • 另外,您如何处理imageUploadStatus?您并没有真正验证是否只保存接受的扩展
  • 这是个坏主意,将图像的数据量存储在会话中......
  • @Darren 是的,我已更改为仅将FileNameFileBytes 存储到Session 中,但问题仍然存在。

标签: c# asp.net image file-upload


【解决方案1】:

正如 Felipe Deguchi 在 cmets 中指出的那样,这个问题只是 this question 的重复。

我只需要补充:

<system.web>
<httpRuntime executionTimeout="90" 
             maxRequestLength="20000" 
             useFullyQualifiedRedirectUrl="false" 
             requestLengthDiskThreshold="8192"/>
</system.web>

在我的Web.config

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2012-09-30
    相关资源
    最近更新 更多