Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# FileUpload控件HasFile始终为False_C#_Asp.net_File Upload - Fatal编程技术网

C# FileUpload控件HasFile始终为False

C# FileUpload控件HasFile始终为False,c#,asp.net,file-upload,C#,Asp.net,File Upload,我的Asp.NETWebForms项目中有一个FileUpload控件,它不运行if(fupostphotocrate.HasFile){}块 以下是相关的aspx页面代码: <asp:UpdatePanel ID="upMain" runat="server"> <ContentTemplate> <div class="form-group"> <label for="txbPostPhotoCreate"&g

我的Asp.NETWebForms项目中有一个FileUpload控件,它不运行
if(fupostphotocrate.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>
我的问题是
fupostphotocrate.HasFile
总是返回
false
,即使我上传了一个文件并且它在
fupostphotocrate
控件中。因此,非相关代码(2)永远不会运行(当
fupostphotocrate
包含文件时,它应该运行)

我可能做错了什么?不相关的代码(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字节(例如blank.txt文件)。我正在尝试上载图像,它们都不是空白大小。我记得几年前就注意到了这个问题。请检查
fupostphotocrate.FileName
instead。我测试了您的代码,效果很好。我需要做的唯一更改是更正
结束标记。这是一个打字错误,抱歉我已经修复了它(仍然有问题)-查看新版本另一个要检查的事项…确保您尝试上载的文件大小大于0字节(例如blank.txt文件)。我正在尝试上载图像,其中没有一个是空白大小。我记得几年前就注意到了这个问题。请改为选中
fupostphotocrate.FileName
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;
}