当文件存在时,WebImage.GetImageFromRequest返回null

时间:2013-05-16 17:01:46

标签: c# html razor input upload

即使有文件,我的WebImage.GetImageFromRequest也会返回null。怎么会这样?

cshtml代码:

@{
    if(IsPost)
    {
        if(Request["upload"] != null)
        {
            image = WebImage.GetImageFromRequest();
            if(image != null)
            {
                // something
            }
        }

        if(Request["btn"] != null)
        {
            // something
        }
    }
}
<form action="" method="post">
    <table>
        <tr>
            <td>
                <p>
                    Upload image:
                </p>
            </td>
            <td>
                <input type="file" name="img" />
                <br/>
                <input type="submit" name="upload" value="Upload" />
            </td>
        </tr>
    </table>
    <input type="submit" name="btn" value="update" />
</form>

3 个答案:

答案 0 :(得分:4)

尝试使用这种替代方法(因为一些错误):

public static WebImage GetImageFromRequest() {
var request = HttpContext.Current.Request;

if (request.Files.Length == 0) {
    return null;
}

try {
    var postedFile = request.Files[0];
    var image = new WebImage(postedFile.InputStream) {
        FileName = postedFile.FileName
    };
    return image;
} catch {
    // The user uploaded a file that wasn't an image or an image format that we don't understand
    return null;
}
}

来自here

答案 1 :(得分:2)

您只需要在enctype标记中添加form属性,如下所示:

<form action="" method="post" enctype="multipart/form-data">

答案 2 :(得分:1)

试试这个:

image = new WebImage(Request.InputStream);

而不是:

image = WebImage.GetImageFromRequest();

来自here