FileUpload控件HasFile始终为False

时间:2016-07-19 10:19:32

标签: c# asp.net file-upload

我的Asp.Net Webforms项目中有一个FileUpload控件,它不会运行if(fuPostPhotoCreate.HasFile) { }块。

这是相关的aspx页面代码:

<asp:UpdatePanel ID="upMain" runat="server">
    <ContentTemplate>
      <div class="form-group">
          <label for="txbPostPhotoCreate">Picture</label>
          <asp:FileUpload ID="fuPostPhotoCreate" runat="server" ToolTip="Upload Picture" />
          <asp:RegularExpressionValidator ID="revPostPhotoCreate" runat="server" ControlToValidate="fuPostPhotoCreate" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.jpeg|.gif)$" CssClass="text-danger" ErrorMessage='Please select a valid image format (".png", ".jpg", ".jpeg" or ".gif")' Display="Dynamic" />
        </div>
        <asp:LinkButton ID="btnCreatePost" runat="server" CssClass="btn btn-success" OnClick="btnCreatePost_Click" CausesValidation="true" ToolTip="Create Post" >
            <span class="glyphicon glyphicon-plus"></span>
            Create Post
        </asp:LinkButton>
    </ContentTemplate>
    <Triggers>
        <asp:PostBackTrigger ControlID="btnCreatePost" />
    </Triggers>
</asp:UpdatePanel>

然后我在aspx.cs页面中有以下内容:

protected void btnCreatePost_Click(object sender, EventArgs e)
{
    // (1) Some non relevant code
    if (fuPostPhotoCreate.HasFile)
    {
        // (2) More non relevant code
    }
    // (3) Final non relevant code
}

我的问题是即使我上传了一个文件并且它位于fuPostPhotoCreate.HasFile控件中,false也始终返回fuPostPhotoCreate。因此,非相关代码(2)永远不会运行(当fuPostPhotoCreate包含文件时它应该运行。

我可能做错了什么?非相关代码(1)和(3)确实成功运行。

修改

以下是该按钮点击的完整代码:

if (!Page.IsValid)
    return;

try
{
    var post = new Models.EF.Post();

    post.DateCreated = DateTime.Now;
    post.Title = txbPostTitleCreate.Text;
    post.Body = txbPostBodyCreate.Text;
    post.IsPublic = cbxPostPublicCreate.Checked;

    int postId = efService.CreatePost(post);
    gvDisplayPosts.DataBind();

    if (fuPostPhotoCreate.HasFile)
    {
        //? Get filename extension
        string fileName = Path.GetFileName(fuPostPhotoCreate.FileName);
        string extension = fileName.Substring(fileName.LastIndexOf('.'));

        //? Specify the path to save the uploaded file to.
        string tempPath = Server.MapPath("~/Uploads/Temp") + "\\" + postId.ToString() + extension;
        string savePath = Server.MapPath("~/Uploads/Posts") + "\\" + postId.ToString() + extension;
        string saveThumbnailPath = Server.MapPath("~/Uploads/Posts/Thumbnails") + "\\" + postId.ToString() + extension;

        #region Remove EXIF Data
        var image = System.Drawing.Image.FromFile(tempPath);

        if (Array.IndexOf(image.PropertyIdList, 274) > -1)
        {
            var orientation = (int)image.GetPropertyItem(274).Value[0];
            switch (orientation)
            {
                case 1:
                    // No rotation required
                    break;
                case 2:
                    image.RotateFlip(RotateFlipType.RotateNoneFlipX);
                    break;
                case 3:
                    image.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    break;
                case 4:
                    image.RotateFlip(RotateFlipType.Rotate180FlipX);
                    break;
                case 5:
                    image.RotateFlip(RotateFlipType.Rotate90FlipX);
                    break;
                case 6:
                    image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    break;
                case 7:
                    image.RotateFlip(RotateFlipType.Rotate270FlipX);
                    break;
                case 8:
                    image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    break;
            }   
            //This EXIF data is now invalid and should be removed.
            image.RemovePropertyItem(274);
        }   

        image.Save(savePath);
        image.Dispose();

        var tempDir = new DirectoryInfo(Server.MapPath("~/Uploads/Temp"));
        foreach (FileInfo file in tempDir.GetFiles())
        {
            file.Delete();
        }
        #endregion

        //? Convert savePath photo to thumnail and save to saveThumbnailPath
        var fullImage = System.Drawing.Image.FromFile(savePath);
        var thumbnailImage = new ImageResizer.ImageJob(fullImage, saveThumbnailPath, new ImageResizer.Instructions("width=150;mode=stretch;autorotate=false"));
        thumbnailImage.Build();

        string dbPathName = "~/Uploads/Posts/" + postId.ToString() + extension;
        string dbThumbnailPath = "~/Uploads/Posts/Thumbnails/" + postId.ToString() + extension;
        efService.SetPostPath(postId, dbPathName);
        efService.SetPostThumbnailPath(postId, dbThumbnailPath);
    }

    //? Clear Fields
    txbPostTitleCreate.Text = string.Empty;
    txbPostBodyCreate.Text = string.Empty;
    cbxPostPublicCreate.Checked = false;

    //? Hide pnlAddPost
    pnlAddPost.Visible = false;
}

catch (Exception ex)
{
    string errorMessage = ex.Message.ToString();
    lblExceptionMessage.Text = errorMessage;

    lblExceptionMessage.Visible = true;
}

注意: 我发现,如果我在提交之前至少更改一次要上传的文件,它似乎有效。

0 个答案:

没有答案