ASP.NET - 使用Session来存储FileUpload对象

时间:2016-10-17 12:57:56

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

我想存储一个FileUpload对象,其中包含Session中的图像。然后在下一页,我想将图像保存到一个文件夹中。我能够毫无问题地做到这一点,但是当我尝试存储更大的图像时,图像变为0kb,而Windows Photo Viewer则表示该文件为空。这是我的代码:

上传表单页面(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) { }
}

1 个答案:

答案 0 :(得分:0)

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

我只需要添加:

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

Web.config