ファイルアップロード ASP.NET MVC 3.0 質問する

ファイルアップロード ASP.NET MVC 3.0 質問する

(前置き:この質問はASP.NET MVC 3.0に関するもので、2011年にリリースされました2019年にリリースされたASP.NET Core 3.0に関するものではありません)

asp.net mvc でファイルをアップロードしたいです。html コントロールを使用してファイルをアップロードするにはどうすればよいでしょうかinput file?

ベストアンサー1

ファイル入力コントロールは使用しません。サーバー側コントロールはASP.NET MVCでは使用されません。次のブログ投稿これは、ASP.NET MVC でこれを実現する方法を示しています。

まず、ファイル入力を含む HTML フォームを作成します。

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

そして、アップロードを処理するコントローラーが作成されます。

public class HomeController : Controller
{
    // This action renders the form
    public ActionResult Index()
    {
        return View();
    }

    // This action handles the form POST and the upload
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // extract only the filename
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");        
    }
}

おすすめ記事