Asp.Net Core 2 - audio files from and to the database












0















I am currently creating a web application that is supposed to play sound files.
The first problem I have encountered is the fact that when writing audio files to a database, all records have the same value even though they are different audio files, database with audio files



I'm not sure if it saves it in a good way, but I wanted to do it in the same way as with pictures



Mp3 mp3 = new Mp3();
using (var memoryStream = new MemoryStream())
{
await createViewModel.Name_mp3.CopyToAsync(memoryStream);
mp3.Name_mp3 = memoryStream.ToArray();
}
_context.Mp3.Add(mp3);
_context.SaveChanges();


Please, give me a hint as to whether it should look like this





The second question is how to extract these audio files from the database. I also tried the way in which pictures were extracted from the database.



So my view looks like this



    @model IEnumerable<inz.Models.Song>

@{
ViewData["Title"] = "Index";
}

<div class="panelDiv textColor">
<form asp-controller="Songs" asp-action="Index" method="get">
<div class="input-group w-50 m-4 mx-auto">
<input type="text" class="form-control input-lg border-danger searchBorder" placeholder="Wyszukaj utwór lub artyste" name="search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="fas fa-search"></i>
</button>
</span>
<div class="dropdown w-0">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>

<div class="dropdown-menu bg-danger" aria-labelledby="dropdownMenuButton">
<input type="submit" name="all" value="Wyświetl wszystko" class="btn btn-danger" />
</div>
</div>
</div>
</form>
<div class="text-center m-5">
<a asp-action=Create>
<buton class="textColor btnDiv">
Dodaj nowy utwór <i class="fas fa-plus-circle fa-lg"></i>
</buton>
</a>
</div>
@if (ViewBag.ShowList == true)
{
<div class="table-responsive">
<table class="table tableSong">
<thead class="bg-danger table-borderless">
<tr>
<th>

</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Album.Name_Album)
</th>
<th>
@Html.DisplayNameFor(model => model.Artist.Name_Artist)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
<i class="fas fa-thumbs-up"></i>
&nbsp;
&nbsp;
<i class="fas fa-thumbs-down"></i>
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@if (item.Album.Name_Album != null)
{
<a asp-controller="Songs" asp-action="Album" asp-route-nameAlbum="@item.Album.Name_Album" class="link">@Html.DisplayFor(modelItem => item.Album.Name_Album)</a>
}
else
{
<span>Brak informacji</span>
}
</td>
<td>
<a asp-controller="Songs" asp-action="Artist" asp-route-name="@item.Artist.Name_Artist" class="link">@Html.DisplayFor(modelItem => item.Artist.Name_Artist)</a>
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Edytuj</buton>
</a>
<a asp-action="Details" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Detale</buton>
</a>

@if (User.IsInRole("Admin"))
{
<a asp-action="Delete" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Usuń</buton>
</a>
}
</td>
**<td>
@{
var base64 = Convert.ToBase64String(item.Mp3.Name_mp3);
var imgSrc = String.Format("data:audio/mp3;base64,{0}", base64);
}
<audio controls>
<source src="@imgSrc" type="audio/ogg" />
</audio>
</td>**
</tr>
}
</tbody>
</table>



</div>
}
else
{
<p class="mt-5"> Brak zawartości do wyświetlenia</p>
}
</div>


But I still have an error



I will add what my models look like



public class Mp3
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID_Mp3 { get; set; }

public byte Name_mp3 { get; set; }
}


and



public class CreateViewModel
{
public int ID_Song { get; set; }

[Required(ErrorMessage = "Proszę wpisać tytuł")]
[Display(Name = "Tytuł")]
public string Title { get; set; }

[Required(ErrorMessage = "Proszę wpisać nazwę artysty")]
[Display(Name = "Artysta")]
public string Name_Artist { get; set; }

[Display(Name = "Album")]
public string Name_Album { get; set; }

[Display(Name = "Producent")]
public string Name_Producer { get; set; }

public IFormFile Name_mp3 { get; set; }
}


I am asking for hints and I apologize for my English










share|improve this question























  • Just a suggestion, have you thought about using blob storage instead?

    – Patrick Goode
    Nov 20 '18 at 22:32
















0















I am currently creating a web application that is supposed to play sound files.
The first problem I have encountered is the fact that when writing audio files to a database, all records have the same value even though they are different audio files, database with audio files



I'm not sure if it saves it in a good way, but I wanted to do it in the same way as with pictures



Mp3 mp3 = new Mp3();
using (var memoryStream = new MemoryStream())
{
await createViewModel.Name_mp3.CopyToAsync(memoryStream);
mp3.Name_mp3 = memoryStream.ToArray();
}
_context.Mp3.Add(mp3);
_context.SaveChanges();


Please, give me a hint as to whether it should look like this





The second question is how to extract these audio files from the database. I also tried the way in which pictures were extracted from the database.



So my view looks like this



    @model IEnumerable<inz.Models.Song>

@{
ViewData["Title"] = "Index";
}

<div class="panelDiv textColor">
<form asp-controller="Songs" asp-action="Index" method="get">
<div class="input-group w-50 m-4 mx-auto">
<input type="text" class="form-control input-lg border-danger searchBorder" placeholder="Wyszukaj utwór lub artyste" name="search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="fas fa-search"></i>
</button>
</span>
<div class="dropdown w-0">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>

<div class="dropdown-menu bg-danger" aria-labelledby="dropdownMenuButton">
<input type="submit" name="all" value="Wyświetl wszystko" class="btn btn-danger" />
</div>
</div>
</div>
</form>
<div class="text-center m-5">
<a asp-action=Create>
<buton class="textColor btnDiv">
Dodaj nowy utwór <i class="fas fa-plus-circle fa-lg"></i>
</buton>
</a>
</div>
@if (ViewBag.ShowList == true)
{
<div class="table-responsive">
<table class="table tableSong">
<thead class="bg-danger table-borderless">
<tr>
<th>

</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Album.Name_Album)
</th>
<th>
@Html.DisplayNameFor(model => model.Artist.Name_Artist)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
<i class="fas fa-thumbs-up"></i>
&nbsp;
&nbsp;
<i class="fas fa-thumbs-down"></i>
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@if (item.Album.Name_Album != null)
{
<a asp-controller="Songs" asp-action="Album" asp-route-nameAlbum="@item.Album.Name_Album" class="link">@Html.DisplayFor(modelItem => item.Album.Name_Album)</a>
}
else
{
<span>Brak informacji</span>
}
</td>
<td>
<a asp-controller="Songs" asp-action="Artist" asp-route-name="@item.Artist.Name_Artist" class="link">@Html.DisplayFor(modelItem => item.Artist.Name_Artist)</a>
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Edytuj</buton>
</a>
<a asp-action="Details" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Detale</buton>
</a>

@if (User.IsInRole("Admin"))
{
<a asp-action="Delete" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Usuń</buton>
</a>
}
</td>
**<td>
@{
var base64 = Convert.ToBase64String(item.Mp3.Name_mp3);
var imgSrc = String.Format("data:audio/mp3;base64,{0}", base64);
}
<audio controls>
<source src="@imgSrc" type="audio/ogg" />
</audio>
</td>**
</tr>
}
</tbody>
</table>



</div>
}
else
{
<p class="mt-5"> Brak zawartości do wyświetlenia</p>
}
</div>


But I still have an error



I will add what my models look like



public class Mp3
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID_Mp3 { get; set; }

public byte Name_mp3 { get; set; }
}


and



public class CreateViewModel
{
public int ID_Song { get; set; }

[Required(ErrorMessage = "Proszę wpisać tytuł")]
[Display(Name = "Tytuł")]
public string Title { get; set; }

[Required(ErrorMessage = "Proszę wpisać nazwę artysty")]
[Display(Name = "Artysta")]
public string Name_Artist { get; set; }

[Display(Name = "Album")]
public string Name_Album { get; set; }

[Display(Name = "Producent")]
public string Name_Producer { get; set; }

public IFormFile Name_mp3 { get; set; }
}


I am asking for hints and I apologize for my English










share|improve this question























  • Just a suggestion, have you thought about using blob storage instead?

    – Patrick Goode
    Nov 20 '18 at 22:32














0












0








0








I am currently creating a web application that is supposed to play sound files.
The first problem I have encountered is the fact that when writing audio files to a database, all records have the same value even though they are different audio files, database with audio files



I'm not sure if it saves it in a good way, but I wanted to do it in the same way as with pictures



Mp3 mp3 = new Mp3();
using (var memoryStream = new MemoryStream())
{
await createViewModel.Name_mp3.CopyToAsync(memoryStream);
mp3.Name_mp3 = memoryStream.ToArray();
}
_context.Mp3.Add(mp3);
_context.SaveChanges();


Please, give me a hint as to whether it should look like this





The second question is how to extract these audio files from the database. I also tried the way in which pictures were extracted from the database.



So my view looks like this



    @model IEnumerable<inz.Models.Song>

@{
ViewData["Title"] = "Index";
}

<div class="panelDiv textColor">
<form asp-controller="Songs" asp-action="Index" method="get">
<div class="input-group w-50 m-4 mx-auto">
<input type="text" class="form-control input-lg border-danger searchBorder" placeholder="Wyszukaj utwór lub artyste" name="search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="fas fa-search"></i>
</button>
</span>
<div class="dropdown w-0">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>

<div class="dropdown-menu bg-danger" aria-labelledby="dropdownMenuButton">
<input type="submit" name="all" value="Wyświetl wszystko" class="btn btn-danger" />
</div>
</div>
</div>
</form>
<div class="text-center m-5">
<a asp-action=Create>
<buton class="textColor btnDiv">
Dodaj nowy utwór <i class="fas fa-plus-circle fa-lg"></i>
</buton>
</a>
</div>
@if (ViewBag.ShowList == true)
{
<div class="table-responsive">
<table class="table tableSong">
<thead class="bg-danger table-borderless">
<tr>
<th>

</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Album.Name_Album)
</th>
<th>
@Html.DisplayNameFor(model => model.Artist.Name_Artist)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
<i class="fas fa-thumbs-up"></i>
&nbsp;
&nbsp;
<i class="fas fa-thumbs-down"></i>
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@if (item.Album.Name_Album != null)
{
<a asp-controller="Songs" asp-action="Album" asp-route-nameAlbum="@item.Album.Name_Album" class="link">@Html.DisplayFor(modelItem => item.Album.Name_Album)</a>
}
else
{
<span>Brak informacji</span>
}
</td>
<td>
<a asp-controller="Songs" asp-action="Artist" asp-route-name="@item.Artist.Name_Artist" class="link">@Html.DisplayFor(modelItem => item.Artist.Name_Artist)</a>
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Edytuj</buton>
</a>
<a asp-action="Details" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Detale</buton>
</a>

@if (User.IsInRole("Admin"))
{
<a asp-action="Delete" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Usuń</buton>
</a>
}
</td>
**<td>
@{
var base64 = Convert.ToBase64String(item.Mp3.Name_mp3);
var imgSrc = String.Format("data:audio/mp3;base64,{0}", base64);
}
<audio controls>
<source src="@imgSrc" type="audio/ogg" />
</audio>
</td>**
</tr>
}
</tbody>
</table>



</div>
}
else
{
<p class="mt-5"> Brak zawartości do wyświetlenia</p>
}
</div>


But I still have an error



I will add what my models look like



public class Mp3
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID_Mp3 { get; set; }

public byte Name_mp3 { get; set; }
}


and



public class CreateViewModel
{
public int ID_Song { get; set; }

[Required(ErrorMessage = "Proszę wpisać tytuł")]
[Display(Name = "Tytuł")]
public string Title { get; set; }

[Required(ErrorMessage = "Proszę wpisać nazwę artysty")]
[Display(Name = "Artysta")]
public string Name_Artist { get; set; }

[Display(Name = "Album")]
public string Name_Album { get; set; }

[Display(Name = "Producent")]
public string Name_Producer { get; set; }

public IFormFile Name_mp3 { get; set; }
}


I am asking for hints and I apologize for my English










share|improve this question














I am currently creating a web application that is supposed to play sound files.
The first problem I have encountered is the fact that when writing audio files to a database, all records have the same value even though they are different audio files, database with audio files



I'm not sure if it saves it in a good way, but I wanted to do it in the same way as with pictures



Mp3 mp3 = new Mp3();
using (var memoryStream = new MemoryStream())
{
await createViewModel.Name_mp3.CopyToAsync(memoryStream);
mp3.Name_mp3 = memoryStream.ToArray();
}
_context.Mp3.Add(mp3);
_context.SaveChanges();


Please, give me a hint as to whether it should look like this





The second question is how to extract these audio files from the database. I also tried the way in which pictures were extracted from the database.



So my view looks like this



    @model IEnumerable<inz.Models.Song>

@{
ViewData["Title"] = "Index";
}

<div class="panelDiv textColor">
<form asp-controller="Songs" asp-action="Index" method="get">
<div class="input-group w-50 m-4 mx-auto">
<input type="text" class="form-control input-lg border-danger searchBorder" placeholder="Wyszukaj utwór lub artyste" name="search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="fas fa-search"></i>
</button>
</span>
<div class="dropdown w-0">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>

<div class="dropdown-menu bg-danger" aria-labelledby="dropdownMenuButton">
<input type="submit" name="all" value="Wyświetl wszystko" class="btn btn-danger" />
</div>
</div>
</div>
</form>
<div class="text-center m-5">
<a asp-action=Create>
<buton class="textColor btnDiv">
Dodaj nowy utwór <i class="fas fa-plus-circle fa-lg"></i>
</buton>
</a>
</div>
@if (ViewBag.ShowList == true)
{
<div class="table-responsive">
<table class="table tableSong">
<thead class="bg-danger table-borderless">
<tr>
<th>

</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Album.Name_Album)
</th>
<th>
@Html.DisplayNameFor(model => model.Artist.Name_Artist)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
<i class="fas fa-thumbs-up"></i>
&nbsp;
&nbsp;
<i class="fas fa-thumbs-down"></i>
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@if (item.Album.Name_Album != null)
{
<a asp-controller="Songs" asp-action="Album" asp-route-nameAlbum="@item.Album.Name_Album" class="link">@Html.DisplayFor(modelItem => item.Album.Name_Album)</a>
}
else
{
<span>Brak informacji</span>
}
</td>
<td>
<a asp-controller="Songs" asp-action="Artist" asp-route-name="@item.Artist.Name_Artist" class="link">@Html.DisplayFor(modelItem => item.Artist.Name_Artist)</a>
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Edytuj</buton>
</a>
<a asp-action="Details" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Detale</buton>
</a>

@if (User.IsInRole("Admin"))
{
<a asp-action="Delete" asp-route-id="@item.ID_Song">
<buton class="textColor btnIndex">Usuń</buton>
</a>
}
</td>
**<td>
@{
var base64 = Convert.ToBase64String(item.Mp3.Name_mp3);
var imgSrc = String.Format("data:audio/mp3;base64,{0}", base64);
}
<audio controls>
<source src="@imgSrc" type="audio/ogg" />
</audio>
</td>**
</tr>
}
</tbody>
</table>



</div>
}
else
{
<p class="mt-5"> Brak zawartości do wyświetlenia</p>
}
</div>


But I still have an error



I will add what my models look like



public class Mp3
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID_Mp3 { get; set; }

public byte Name_mp3 { get; set; }
}


and



public class CreateViewModel
{
public int ID_Song { get; set; }

[Required(ErrorMessage = "Proszę wpisać tytuł")]
[Display(Name = "Tytuł")]
public string Title { get; set; }

[Required(ErrorMessage = "Proszę wpisać nazwę artysty")]
[Display(Name = "Artysta")]
public string Name_Artist { get; set; }

[Display(Name = "Album")]
public string Name_Album { get; set; }

[Display(Name = "Producent")]
public string Name_Producer { get; set; }

public IFormFile Name_mp3 { get; set; }
}


I am asking for hints and I apologize for my English







c# database asp.net-core-2.0






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 22:11









CobraCobra

1




1













  • Just a suggestion, have you thought about using blob storage instead?

    – Patrick Goode
    Nov 20 '18 at 22:32



















  • Just a suggestion, have you thought about using blob storage instead?

    – Patrick Goode
    Nov 20 '18 at 22:32

















Just a suggestion, have you thought about using blob storage instead?

– Patrick Goode
Nov 20 '18 at 22:32





Just a suggestion, have you thought about using blob storage instead?

– Patrick Goode
Nov 20 '18 at 22:32












1 Answer
1






active

oldest

votes


















0














I don't think that storing the audio files in the database it's a good idea.



You could instead save the file on disk, then save the path.



public class File
{
[Key]
public Guid Id { get; set; }
[Required]
public string Name{ get; set; }
[Required]
public string Path { get; set; }
[Required]
public DateTime Registered{ get; set; }
[Required]
public string RegisteredBy { get; set; }
public string Notes { get; set; }
}


To save the file:



using (var db = new EFModel())
{
if (file.Id == Guid.Empty)
{
file.Id = Guid.NewGuid();
db.Entry(file).State = EntityState.Added;
}
else
db.Entry(file).State = EntityState.Modified;

db.SaveChanges();
return archivo;
}


In the save button/action:



if (!fuArchivo.HasFile)
throw new UserException("Debes seleccionar un archivo.");

string nombreArchivo = Path.GetFileNameWithoutExtension(fuArchivo.FileName);
string extension = Path.GetExtension(fuArchivo.FileName);

string pathArchivo = Path.Combine(ConfigurationManager.AppSettings["rutaCarga"],
ae.IdTitulo.ToString(), ae.IdArchivoEtapa.ToString());
if (!Directory.Exists(pathArchivo))
Directory.CreateDirectory(pathArchivo);
pathArchivo = Path.Combine(pathArchivo, Guid.NewGuid().ToString() + extension);

fuArchivo.SaveAs(pathArchivo);
if (File.Exists(pathArchivo))
{
var archivo = new File()
{
Id = Guid.Empty,
RegisteredBy = ClaimsPrincipal.Current.Identity.Name,
Registered = DateTime.Now,
Name = nombreArchivo,
Path = pathArchivo
};
var on = new FileBO();
return on.Save(archivo);
}
else
throw new Exception("Se guardó el archivo pero no existe.");


Sorry, it's in spanish. Hope this helps.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402373%2fasp-net-core-2-audio-files-from-and-to-the-database%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I don't think that storing the audio files in the database it's a good idea.



    You could instead save the file on disk, then save the path.



    public class File
    {
    [Key]
    public Guid Id { get; set; }
    [Required]
    public string Name{ get; set; }
    [Required]
    public string Path { get; set; }
    [Required]
    public DateTime Registered{ get; set; }
    [Required]
    public string RegisteredBy { get; set; }
    public string Notes { get; set; }
    }


    To save the file:



    using (var db = new EFModel())
    {
    if (file.Id == Guid.Empty)
    {
    file.Id = Guid.NewGuid();
    db.Entry(file).State = EntityState.Added;
    }
    else
    db.Entry(file).State = EntityState.Modified;

    db.SaveChanges();
    return archivo;
    }


    In the save button/action:



    if (!fuArchivo.HasFile)
    throw new UserException("Debes seleccionar un archivo.");

    string nombreArchivo = Path.GetFileNameWithoutExtension(fuArchivo.FileName);
    string extension = Path.GetExtension(fuArchivo.FileName);

    string pathArchivo = Path.Combine(ConfigurationManager.AppSettings["rutaCarga"],
    ae.IdTitulo.ToString(), ae.IdArchivoEtapa.ToString());
    if (!Directory.Exists(pathArchivo))
    Directory.CreateDirectory(pathArchivo);
    pathArchivo = Path.Combine(pathArchivo, Guid.NewGuid().ToString() + extension);

    fuArchivo.SaveAs(pathArchivo);
    if (File.Exists(pathArchivo))
    {
    var archivo = new File()
    {
    Id = Guid.Empty,
    RegisteredBy = ClaimsPrincipal.Current.Identity.Name,
    Registered = DateTime.Now,
    Name = nombreArchivo,
    Path = pathArchivo
    };
    var on = new FileBO();
    return on.Save(archivo);
    }
    else
    throw new Exception("Se guardó el archivo pero no existe.");


    Sorry, it's in spanish. Hope this helps.






    share|improve this answer




























      0














      I don't think that storing the audio files in the database it's a good idea.



      You could instead save the file on disk, then save the path.



      public class File
      {
      [Key]
      public Guid Id { get; set; }
      [Required]
      public string Name{ get; set; }
      [Required]
      public string Path { get; set; }
      [Required]
      public DateTime Registered{ get; set; }
      [Required]
      public string RegisteredBy { get; set; }
      public string Notes { get; set; }
      }


      To save the file:



      using (var db = new EFModel())
      {
      if (file.Id == Guid.Empty)
      {
      file.Id = Guid.NewGuid();
      db.Entry(file).State = EntityState.Added;
      }
      else
      db.Entry(file).State = EntityState.Modified;

      db.SaveChanges();
      return archivo;
      }


      In the save button/action:



      if (!fuArchivo.HasFile)
      throw new UserException("Debes seleccionar un archivo.");

      string nombreArchivo = Path.GetFileNameWithoutExtension(fuArchivo.FileName);
      string extension = Path.GetExtension(fuArchivo.FileName);

      string pathArchivo = Path.Combine(ConfigurationManager.AppSettings["rutaCarga"],
      ae.IdTitulo.ToString(), ae.IdArchivoEtapa.ToString());
      if (!Directory.Exists(pathArchivo))
      Directory.CreateDirectory(pathArchivo);
      pathArchivo = Path.Combine(pathArchivo, Guid.NewGuid().ToString() + extension);

      fuArchivo.SaveAs(pathArchivo);
      if (File.Exists(pathArchivo))
      {
      var archivo = new File()
      {
      Id = Guid.Empty,
      RegisteredBy = ClaimsPrincipal.Current.Identity.Name,
      Registered = DateTime.Now,
      Name = nombreArchivo,
      Path = pathArchivo
      };
      var on = new FileBO();
      return on.Save(archivo);
      }
      else
      throw new Exception("Se guardó el archivo pero no existe.");


      Sorry, it's in spanish. Hope this helps.






      share|improve this answer


























        0












        0








        0







        I don't think that storing the audio files in the database it's a good idea.



        You could instead save the file on disk, then save the path.



        public class File
        {
        [Key]
        public Guid Id { get; set; }
        [Required]
        public string Name{ get; set; }
        [Required]
        public string Path { get; set; }
        [Required]
        public DateTime Registered{ get; set; }
        [Required]
        public string RegisteredBy { get; set; }
        public string Notes { get; set; }
        }


        To save the file:



        using (var db = new EFModel())
        {
        if (file.Id == Guid.Empty)
        {
        file.Id = Guid.NewGuid();
        db.Entry(file).State = EntityState.Added;
        }
        else
        db.Entry(file).State = EntityState.Modified;

        db.SaveChanges();
        return archivo;
        }


        In the save button/action:



        if (!fuArchivo.HasFile)
        throw new UserException("Debes seleccionar un archivo.");

        string nombreArchivo = Path.GetFileNameWithoutExtension(fuArchivo.FileName);
        string extension = Path.GetExtension(fuArchivo.FileName);

        string pathArchivo = Path.Combine(ConfigurationManager.AppSettings["rutaCarga"],
        ae.IdTitulo.ToString(), ae.IdArchivoEtapa.ToString());
        if (!Directory.Exists(pathArchivo))
        Directory.CreateDirectory(pathArchivo);
        pathArchivo = Path.Combine(pathArchivo, Guid.NewGuid().ToString() + extension);

        fuArchivo.SaveAs(pathArchivo);
        if (File.Exists(pathArchivo))
        {
        var archivo = new File()
        {
        Id = Guid.Empty,
        RegisteredBy = ClaimsPrincipal.Current.Identity.Name,
        Registered = DateTime.Now,
        Name = nombreArchivo,
        Path = pathArchivo
        };
        var on = new FileBO();
        return on.Save(archivo);
        }
        else
        throw new Exception("Se guardó el archivo pero no existe.");


        Sorry, it's in spanish. Hope this helps.






        share|improve this answer













        I don't think that storing the audio files in the database it's a good idea.



        You could instead save the file on disk, then save the path.



        public class File
        {
        [Key]
        public Guid Id { get; set; }
        [Required]
        public string Name{ get; set; }
        [Required]
        public string Path { get; set; }
        [Required]
        public DateTime Registered{ get; set; }
        [Required]
        public string RegisteredBy { get; set; }
        public string Notes { get; set; }
        }


        To save the file:



        using (var db = new EFModel())
        {
        if (file.Id == Guid.Empty)
        {
        file.Id = Guid.NewGuid();
        db.Entry(file).State = EntityState.Added;
        }
        else
        db.Entry(file).State = EntityState.Modified;

        db.SaveChanges();
        return archivo;
        }


        In the save button/action:



        if (!fuArchivo.HasFile)
        throw new UserException("Debes seleccionar un archivo.");

        string nombreArchivo = Path.GetFileNameWithoutExtension(fuArchivo.FileName);
        string extension = Path.GetExtension(fuArchivo.FileName);

        string pathArchivo = Path.Combine(ConfigurationManager.AppSettings["rutaCarga"],
        ae.IdTitulo.ToString(), ae.IdArchivoEtapa.ToString());
        if (!Directory.Exists(pathArchivo))
        Directory.CreateDirectory(pathArchivo);
        pathArchivo = Path.Combine(pathArchivo, Guid.NewGuid().ToString() + extension);

        fuArchivo.SaveAs(pathArchivo);
        if (File.Exists(pathArchivo))
        {
        var archivo = new File()
        {
        Id = Guid.Empty,
        RegisteredBy = ClaimsPrincipal.Current.Identity.Name,
        Registered = DateTime.Now,
        Name = nombreArchivo,
        Path = pathArchivo
        };
        var on = new FileBO();
        return on.Save(archivo);
        }
        else
        throw new Exception("Se guardó el archivo pero no existe.");


        Sorry, it's in spanish. Hope this helps.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 22:51









        David IllescasDavid Illescas

        1




        1
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402373%2fasp-net-core-2-audio-files-from-and-to-the-database%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Hercules Kyvelos

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud