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

标签 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>

最佳答案

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

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

关于c# - 当文件存在时,WebImage.GetImageFromRequest 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16593366/

相关文章:

c# - 数据模型中没有为 TextBox Text 属性调用 Setter

jQuery 设置样式

html - 如何检查浏览器是否可以通过 html5 视频标签播放 mp4?

c# - 如何使用用户选择的背景颜色覆盖图标的默认背景?

c# - 如何使用 Razor 单选按钮正确实现 MVC3?

c# - 一种将一个列表转换为另一个列表的方法(通过多态性、子类和父类)

c# - 无法在 Visual Studio 2017 中复制文件 .exe

c# - 解决 C# 利息问题,如何计算储蓄余额达到预期目标余额所需的年数?

鼠标悬停时的 jQuery 图像 PULSE 动画,淡入另一个图像

c# - MVC 将 View 组件文件放在哪里