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

本文关键字:GetImageFromRequest 返回 null 文件 存在 WebImage | 更新日期: 2023-09-27 18:13:51

我的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>

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

尝试使用这个替代方法(因为一些bug):

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;
}
}
从这里

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

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

试试这个:

image = new WebImage(Request.InputStream);

代替:

image = WebImage.GetImageFromRequest();
从这里

相关文章:
  • 没有找到相关文章