0

Books という名前のフォルダーにパスを含むファイルをアップロードするコードを次に示します。パスのみをデータベースに保存し、パスに基づいて Books フォルダーからファイルをフェッチします。以下は私のコードで、私はasp.net mvc 4とエンティティフレームワークを使用しています。

    [HttpPost]
    public ActionResult upload(HttpPostedFileBase file)
    {
        //verify that the file is selected and not empty
        if (file != null && file.ContentLength > 0)
        {
            //getting the name of the file
            var fileName = Path.GetFileName(file.FileName);

            //store file in the Books folder
            var path = Path.Combine(Server.MapPath("~/BOOKS"), fileName);
            file.SaveAs(path);
        }
        return View();
    }
4

1 に答える 1

2

私の理解が正しければ、ブック パスの文字列をデータベースに保存し、ブック ファイルを ~/Books の下に保存しますか?

  • 「~/Books」の部分はすでに保存されています
  • いくつかのフィールド (ID、BookTitle、BookPath) を含むデータベース テーブルを作成し、モデルをアプリケーションに取り込み (選択した方法、エンティティ フレームワークなど)、ロジックをコーディングします。
    [HttpPost]
    public ActionResult upload(HttpPostedFileBase file)
    {
        //verify that the file is selected and not empty
        if (file != null && file.ContentLength > 0)
        {
            //getting the name of the file
            var fileName = Path.GetFileName(file.FileName);

            //store file in the Books folder
            var path = Path.Combine(Server.MapPath("~/BOOKS"), fileName);
            try{
                file.SaveAs(path);
                db.Table.Add(new Book{BookTitle: "Whatever", BookPath: path});
                db.SaveChanges();
            }catch(Exception ex){

            }
        }
        return View();
    }
于 2012-11-20T14:24:18.907 に答える