簡體   English   中英

如何在數據庫中保存文件路徑?

[英]How to save a file path at database?

我正在使用uploadify插件將音樂上傳到我的應用程序,上傳正常,但是,當我保存路徑引用(音樂保存在我的項目中)時,我得到了空值,任何人知道我該怎么做?

MusicController上的上傳方法

public ActionResult Upload()
{
    var file = Request.Files["Filedata"];
    string savePath = Server.MapPath(@"~\mp3\" + file.FileName);
    file.SaveAs(savePath);
    return Content(Url.Content(@"~\mp3\" + file.FileName));
}

在MusicController上創建方法

  public ActionResult Create(Musica musica)
        {
            MembershipUser user = Membership.GetUser();
            int userId = Int32.Parse(Membership.GetUser().ProviderUserKey.ToString());
            string userName = user.UserName;

            musica.UserId = userId;
            musica.NomeArtista = userName;

            if (musica.isFree)
            {

                musica.Preco = 0;
            }

            //Here I try to take the path value
            musica.path = Upload().ToString();

            if (ModelState.IsValid)
            {
                db.Musicas.Add(musica);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.GeneroId = new SelectList(db.Generos, "GeneroId", "Nome", musica.GeneroId);
            return View(musica);
        }

在這種情況下,我只想在數據庫中保存以下信息:

~\mp3\MusicExample.mp3

有人可以幫我嗎?

編輯:因此,您正在使用的上載方法是異步的,它會上載文件並將文件路徑返回到頁面。 更改上載方法以返回所需的文件路徑,在jQuery中捕獲它,並創建一個在上載信息后保存信息的控件:

您的上傳方法應為:

public ActionResult Upload()
{
    var file = Request.Files["Filedata"];
    string savePath = Server.MapPath(@"~\mp3\" + file.FileName);
    file.SaveAs(savePath);
    return Content(@"~\mp3\" + file.FileName);
}

在您的視圖中的某處,為path屬性添加一個控件:

@Html.EditorFor(model => model.path, new { id = "path"})

在javascript中,捕獲返回值,並將其設置在musica中path屬性的新文本框中:

'onUploadSuccess': function (file, data, response) {
                $("#path").val(data);
            }

在create方法中,刪除代碼以調用Upload

//Stuff above here
if (musica.isFree)
{
    musica.Preco = 0;
}

//Here I try to take the path value
//musica.path = Upload().ToString();

if (ModelState.IsValid)
//stuff below here

現在,當您單擊創建按鈕時,它將自動將path屬性設置為文件路徑,並且應該可以正常工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM