2

这是我的控制器:

public ActionResult Create()

    {
        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
        return View();
    } 

    //
    // POST: /ManagePhotos/Create

    [HttpPost]
    public ActionResult Create(Photo photo, HttpPostedFile file)
    {
        if (ModelState.IsValid)
        {
            if (file != null && file.ContentLength > 0)
            {
                // save as original size of image
                var newfileName = Guid.NewGuid().ToString() + "_"
                                    + Path.GetFileName(file.FileName);
                var bigImagePath = Path.Combine(Server.MapPath("~/Content/PublicPhotos/BigImages"), newfileName);
                file.SaveAs(bigImagePath);

                // save as thumbnail image
                var photoUploaded = new WebImage(bigImagePath);
                photoUploaded.Resize(width: 200, height: 150, preserveAspectRatio: true, preventEnlarge: true);

                var thumbImagePath = Path.Combine(Server.MapPath("~/Content/PublicPhotos/ThumbImages"), newfileName);

                photoUploaded.Save(thumbImagePath);

            }

            db.Photos.Add(photo);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }

这是我的观点:

@using (Html.BeginForm("Create","ManagePhotos", FormMethod.Post, new {enctype = "multipart/form-data"})) 
{

@Html.ValidationSummary(true)
<fieldset>
    <legend>Photo</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.CategoryID, "Category")
    </div>
    <div class="editor-field">
        @Html.DropDownList("CategoryID", String.Empty)
        @Html.ValidationMessageFor(model => model.CategoryID)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.Label("File name: ")
    </div>
    <div class="editor-field">
        <input type="file" name="file"/>
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

}

我的问题:当我按下“创建”按钮时,网页显示如下:

连接被重置。

加载页面时重置与服务器的连接。

该站点可能暂时不可用或太忙。请稍后再试。如果您无法加载任何页面,请检查您计算机的网络连接。如果您的计算机或网络受到防火墙或代理的保护,请确保允许 Firefox 访问 Web。

我尝试在 Razor View 中进行调试,并在这个网站上查找,我确实做了网站向我展示的内容,但我无法弄清楚。请帮我。

4

1 回答 1

1

您的操作是预期的HttpPostedFile,但您应该使用HttpPostedFileBase

同样如评论中所述,您需要验证大小不是太大,您可以在 Javascript 中执行此操作

function onSelectImage(e) {
    if (e.files[0].size > 256000) {
        alert('The file size is too large for upload');
        e.preventDefault();
        return false;
    }
    ...
    return true;
}

例如,这确保图像只有 256K 或更少

于 2012-05-21T14:29:42.633 回答