首页 > 解决方案 > 为什么 file.PostedFile 总是为空

问题描述

我需要将图像上传到我的数据库,为此我需要将它们带到服务器端。唯一的问题是该文件始终为空,我无法使用它。

html:

<form id="signUpForm" runat="server" action="signUp.aspx" method = "get" name = "signUp" 
enctype="multipart/form-data" onsubmit = "return validateSignUp();">
    <div id = "input">
    <table>
        <tr>
        <td class = "description">*profile image: </td>
        <td class = "input" id = "inputProfileImage"><input type = "file" name = "profileImage" accept = "image/png, image/jpeg, image/jpg" id = "profileImage" runat="server"/>
            <div class = "warning" id = "warnProfileImage"></div>

            </td>
        </tr>

        <tr>
        <td><input type = "submit" value = "sign up"/></td>
        <td><input type = "reset" value = "reset"/></td>
        </tr>

    </table>

    </div>

    <div id = "showInfo">
    <table>

        <tr><td class = "description">profile image:</td><td class = "input"><img src = "defaultProfileImages/defaultProfileImage1.png" id = "showProfileImage" name="showProfileImage" runat="server"/></td></tr>

        <tr><td><input type = "submit" name = "submit" value = "confirm"/></td></tr>

    </table>
    </div>
    </form>

C#:

if (Request.QueryString["submit"] != null)
    {
        string path = "";
        if ((profileImage.PostedFile != null) && (profileImage.PostedFile.ContentLength > 0))
        {
            string fn = System.IO.Path.GetFileName(profileImage.PostedFile.FileName);
            string SaveLocation = Server.MapPath("Temp") + "\\" + fn;
            path = SaveLocation;
            try
            {
                profileImage.PostedFile.SaveAs(SaveLocation);
                Response.Write("The file has been uploaded.");
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
                //Note: Exception.Message returns a detailed message that describes the current exception. 
                //For security reasons, we do not recommend that you return Exception.Message to end users in 
                //production environments. It would be better to put a generic error message. 
            }
        }
        User user = new User(Libary.convertFile(path));
        UserService userService = new UserService();
        userService.InsertUser(user);
        Response.Redirect("homePage.aspx");
        Response.End();
    }

*我删除了所有与文件无关的行。

标签: c#htmlasp.net

解决方案


尝试使用HttpPostedFileBase而不是PostedFile快速解决问题。


推荐阅读