1

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>
4

3 回答 3

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;
}
}

这里

于 2013-05-16T17:31:21.337 回答
2

您只需将enctype属性添加到您的form标签,如下所示:

<form action="" method="post" enctype="multipart/form-data">
于 2013-05-16T20:00:13.147 回答
1

尝试这个:

image = new WebImage(Request.InputStream);

代替:

image = WebImage.GetImageFromRequest();

这里

于 2013-05-16T17:39:26.747 回答