MVC getting a list of mp3 and image into a table

2019-09-02 16:02发布

问题:

I have already plug in the codes for uploading files and its working but the problem is I want to upload image to be in image name table, music in music table column, and one more thing is I not getting from any database just directory folder will do.

Here's my razor html all my files are upload into a directory, is there a code to get the extension of .jpg into image column and mp3 to mp3 column? Or is there anyway of coding it

<table>   
@foreach (var f in Directory.GetFiles(Server.MapPath(@ViewBag.UploadURL)))
    {
        var fileInfo = new FileInfo(f);

        ViewBag.FileNoExtension = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('.'));
        ViewBag.FileExtension = fileInfo.Name.Substring(fileInfo.Name.IndexOf('.') + 1);
        <tr>
           <td style = width = "10">@fileInfo.Name</td>
            @* <td>@ViewBag.FileNoExtension</td>*@
          <td><img width="50" height="50" src="@Url.Content(@ViewBag.UploadURL + "/" + fileInfo.Name)" /></td>


                <td>
                   @foreach(var a in Directory.GetFiles(Server.MapPath(@ViewBag.MusicURL)))
                        {  var fileInfoc = new FileInfo(a);
                                      //ViewBag.FileNoExtension = fileInfoc.Name.Substring(0, fileInfoc.Name.IndexOf('.'));
                                      ViewBag.FileExtensionc = fileInfoc.Name.Substring(fileInfoc.Name.IndexOf('.') + 1);                 

                       @fileInfoc.Name     
                         } 

                </td>
                }
                <td>            
                  @Html.ActionLink("Remove", "Remove", new { id = @ViewBag.StoryID, id2 = @ViewBag.FileNoExtension, id3 = @ViewBag.FileExtension })
                </td>

        </tr>
    } </table>

ok heres my controller

   [HttpPost]
    public ActionResult Upload(int id, IEnumerable<HttpPostedFileBase> ImageInput,IEnumerable<HttpPostedFileBase> MP3Input)
    {
        story story = db.stories.Find(id);
        ViewBag.StoryID = story.StoryID;

        ViewBag.MusicURL = "~/Upload/story/Music" + "/" + story.FileURL;
        ViewBag.ImageURL = "~/Upload/story/Image" + "/" + story.FileURL;

        CreateDirectory("~/Upload/story/Music" + "/" + story.FileURL);
        CreateDirectory("~/Upload/story/Image" + "/" + story.FileURL);


        String filepathMusic = "~/Upload/story/Music" + "/" + story.FileURL;
        String filepathImage = "~/Upload/story/Image" + "/" + story.FileURL;

        // get images jpg file only
        foreach (var imagefile in ImageInput)
        {
            if (imagefile != null)
            {
                string extension = Path.GetExtension(imagefile.FileName);
                var fileName = imagefile.FileName;
                var imagePath = Path.Combine(Server.MapPath(filepathImage), fileName);
                switch (extension)
                {
                  //  case ".mp3":
                    case ".jpg":
                         var f = Directory.GetFiles(Server.MapPath(filepathImage));

        var uploadedFiles = new List<String>();
        var files = Directory.GetFiles(Server.MapPath(filepathImage));


        foreach(var file2 in files)
        {
            var fileInfo = new FileInfo(file2);
            uploadedFiles.Add(fileInfo.Name);
            ViewBag.b = fileInfo;
        }
        imagefile.SaveAs(imagePath);

                        //Upload file as it is an image
                        break;
                    default:
                        //Not an image - ignore
                        break;
                }
               // return View("Upload");

                //file.SaveAs(imagePath);
            }
        }
        // get music files only

        foreach (var Musicfile in MP3Input)
        {
            if (Musicfile != null)
            {
                string extension = Path.GetExtension(Musicfile.FileName);
                var filemusic = Musicfile.FileName;
                var MusicPath = Path.Combine(Server.MapPath(filepathMusic), filemusic);
                switch (extension)
                {
                    case ".mp3":
                        var a = Directory.GetFiles(Server.MapPath(filepathMusic));

                        var uploadedFiles = new List<String>();
                        var filesc = Directory.GetFiles(Server.MapPath(filepathMusic));

                        foreach (var file3 in filesc)
                        {
                            var fileInfoc = new FileInfo(file3);
                            uploadedFiles.Add(fileInfoc.Name);
                            ViewBag.a = fileInfoc;
                        }
                        Musicfile.SaveAs(MusicPath);
                  //  case ".jpg":
                        //Upload file as it is an mp3
                        break;
                    default:
                        //Not an mp3 - ignore
                        break;
                }


                //file.SaveAs(imagePath);
            }
        }

回答1:

I have assumed you have some form of common naming to relate the images to the names. For this example I have simply assigned the images to the MP3 files in sequence.

  1. Do the messy work in the controller, not your view. Keep views simple.
  2. Use a View model for the content that is closer to what your view needs.
  3. Get the controller to do the messy work of converting raw facts into the view model.
  4. Controller then passes view mode to view to display it.

Your view should be simple like this:

@model IEnumerable<SomeWebApplication.Models.MusicItem>
<table class="display" id="example">
    <thead>
        <tr>
            <th>Image File</th>
            <th>MP3 File</th>
            <th>Remove</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td><img width="50" height="50" src="@item.ImageUrl" /></td>
                <td><embed src="@item.MusicUrl" /></td>
                <td>@Html.ActionLink("Remove", "Remove", new { id = @item.Id })</td>
            </tr>
        }
    </tbody>
</table>

...it takes a collection of MusicItems as its View Model

The View Model will look like:

public class MusicItem
{
    /// <summary>
    /// Unique id of item
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// URL to image
    /// </summary>
    public string ImageUrl { get; set; }

    /// <summary>
    /// Url to music
    /// </summary>
    public string MusicUrl { get; set; }
}

Your controller should do the heavy lifting:

    public ActionResult Details(int id)
    {
        Story story = db.Stories.Find(id);

        // Use server relative paths for views
        String filepathMusic = "/Upload/story/Music/" + story.FileURL;
        String filepathImage = "/Upload/story/Image/" + story.FileURL;

        // Build a list of MusicItem objects
        List<MusicItem> items = new List<MusicItem>();
        string[] musicFiles = Directory.GetFiles(Server.MapPath("~" + filepathMusic));
        foreach (var musicFile in musicFiles)
        {
            items.Add(new MusicItem()
            {
                Id = id,
                MusicUrl = filepathMusic + "/" + Path.GetFileName(musicFile)
            });
        }

        // This example simply allocates the images in the order found - need to do this properly
        string[] imageFiles = Directory.GetFiles(Server.MapPath("~" + filepathImage));
        int index = 0;
        foreach (var imageFile in imageFiles)
        {
            if (index < items.Count)
            {
                items[index].ImageUrl = filepathImage + "/" + Path.GetFileName(imageFile);
            }
            index++;
        }

        return View(items);
    }

then, assuming you have 2 images and two files in your story...

The end result of the test code above looks like this: