Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add FileUpload dynamically with a different name field

I need the ability to add multiple file uploads based on the user needs BUT the user has to be able to assign a name to the upload for later usage. As you can see I'm only dynamically adding more file uploads but assign a name to these uploads seems to be my problem. Is there any way I can achieve this?

Screenshot how it is at the moment

The code in my View :

@using Microsoft.Web.Helpers
@model MusicNews.Web.Models.ViewModel.ArticleCreateModel

@{
    ViewBag.Title = "Create";
}

@section content
{

        @using (Html.BeginForm("Create", "Article", FormMethod.Post,
                      new { enctype = "multipart/form-data" }))
        {
                ...

                @FileUpload.GetHtml("Files",2,true,false,"Add more")

                <p>
                    <input type="submit" value="Create" />
                </p>
        }
}

The code in my controller looks like :

[Authorize]
public ActionResult Create()
{
    ViewBag.ArticleTypes = new SelectList(ArticleTypes, "Type");
    return View();
}


[HttpPost]
[Authorize]
public ActionResult Create(ArticleCreateModel article)
{
    var files = Request.Files;

    if (ModelState.IsValid)
    {
        ...
    }
    return View(article);
}
like image 787
Tom Kerkhove Avatar asked Oct 06 '22 12:10

Tom Kerkhove


1 Answers

You probably have to create additional uploads yourself. This can be done using jQuery, for example:

Here's the HTML:

<div id="uploads">
    <div id="uploadtemplate">
        <input type="file" name="upload" />
        <input type="text" name="FileName" />
    <div>

    <a href="#" id="addFile">Add file</a>
</div>

On load, we'll clone the "template" in a variable for later use. On click, we'll clone the template and add it to the document.

$(function() {/
    $('#addFile').data('uploadtemplate', $('#uploadtemplate').attr('id', '').clone());

    $('#addFile').click(function(e) {
        $(this).data('uploadtemplate').clone().insertBefore( $this) );

        e.preventDefault();
    });
});

Your model will be:

public class Foo {
    public string[] FileName { get; set; } // will contain all file names given by the user
}

Then parse Request.Files and do the magic you know :-) The Foo.FileName field wil lcontain a file name given by the user for every uploaded file. You can use that as the first file in Request.Files will map to Foo.FileName[0] and so on.

like image 149
maartenba Avatar answered Oct 10 '22 02:10

maartenba