How to save a file path at database?

13.6k views Asked by At

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

There are 1 answers

8
Dave Zych On BEST ANSWER

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