41

アップロードフォームがあり、画像やその他のフィールドなどの情報を渡したいのですが、画像をアップロードする方法がわかりません。

これは私のコントローラーコードです:

[HttpPost]
        public ActionResult Create(tblPortfolio tblportfolio)
        {
            if (ModelState.IsValid)
            {
                db.tblPortfolios.AddObject(tblportfolio);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(tblportfolio);
        }

そしてこれは私のビューコードです:

@model MyApp.Models.tblPortfolio

<h2>Create</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>tblPortfolio</legend>

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

        <div class="editor-label">
            @Html.LabelFor(model => model.ImageFile)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.ImageFile, new { type = "file" })
            @Html.ValidationMessageFor(model => model.ImageFile)
        </div>

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

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

画像をアップロードしてサーバーに保存する方法がわかりません。画像名を設定するにはどうすればよいですかGuid.NewGuid();。または、どうすれば画像パスを設定できますか?

4

2 に答える 2

45

まず、以下を含むようにビューを変更する必要があります。

<input type="file" name="file" />

次に、次のように、投稿ActionMethodを変更して を取得する必要があります。HttpPostedFileBase

[HttpPost]
public ActionResult Create(tblPortfolio tblportfolio, HttpPostedFileBase file)
{
    //you can put your existing save code here
    if (file != null && file.ContentLength > 0) 
    {
        //do whatever you want with the file
    }
}
于 2012-05-01T18:29:20.863 に答える