How to save a file path at database?

断了今生、忘了曾经 提交于 2020-01-05 07:31:11

问题


i'm doing a music upload to my application, using the uploadify plugin, the upload are working, but, when i'll save the path reference (where the music are saved on my project), i'm getting null value, anyone knows how can I do this?

Upload Method at 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));
}

Create Method at 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);
        }

On this case, I only want to save in my database, this information:

~\mp3\MusicExample.mp3

Someone can help me?


回答1:


EDIT: So the upload method you're using is asynchronous, and it uploads the file and returns the file path back to the page. Change the upload method to return the file path you want, capture it in the jQuery and create a control that holds the information after it's uploaded:

Your upload method should be this:

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

Somwhere in your view, add a control for the path property:

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

In the javascript, capture the return value and set it inside the new textbox for the path property in musica:

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

In the create method, remove the code to call 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

Now, when you click on the create button, it should automatically set the path property to the file path, and it should just work



来源:https://stackoverflow.com/questions/26897132/how-to-save-a-file-path-at-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!