Using bootstrap fileinput with .NET core

658 views Asked by At

I'm trying to use Krajee's Bootstrap Fileinput (http://plugins.krajee.com/file-input) and having some problems.

The input field is in a form which has a submit button

<form method="post" enctype="multipart/form-data" asp-action="CreeAnnonce" asp-controller="Vendeur">

My problem is when I upload files with the Fileinput, it runs the action method CreeAnnonce as if I click on the submit button of the form

enter image description here

public async Task<IActionResult> CreeAnnonce(Annonce annonce, IFormFile[] photo)
    {
        ...

I would like to run another action method (in AJAX) when I click on "upload" but I don't know how.

Please help me

2

There are 2 answers

0
Yiyi You On

I would like to run another action method (in AJAX) when I click on "upload" but I don't know how.

You can try to add onsubmit to form,and call ajax with onsubmit:

<form method="post" enctype="multipart/form-data" onsubmit="return handleClick()">
    <input id="input-b2" name="input-b2" type="file" class="file" data-show-preview="false">
</form>

js:

function handleClick() {
            alert("handleClick");
        }

result: enter image description here

0
Ali reza Soleimani Asl On

First of all, you need this code on Upload.cshtml Section:

<link href="~/lib/fileUpload/css/fileinput.css" media="all" rel="stylesheet" type="text/css" />
<link href="~/lib/fileUpload/themes/explorer-fas/theme.css" media="all" rel="stylesheet" type="text/css" />
<script src="~/lib/fileUpload/js/plugins/piexif.js" type="text/javascript"></script>
<script src="~/lib/fileUpload/js/plugins/sortable.js" type="text/javascript"></script>
<script src="~/lib/fileUpload/js/fileinput.js" type="text/javascript"></script>
<script src="~/lib/fileUpload/js/locales/fr.js" type="text/javascript"></script>
<script src="~/lib/fileUpload/js/locales/es.js" type="text/javascript"></script>
<script src="~/lib/fileUpload/themes/fas/theme.js" type="text/javascript"></script>
<script src="~/lib/fileUpload/themes/explorer-fas/theme.js" type="text/javascript"></script>

<form asp-action="Upload" enctype="multipart/form-data">
            <input type="hidden" value="8" id="GalleryID" name="GalleryID" />
            <div class="file-loading">
                <input id="kv-explorer" name="files" type="file" multiple>
            </div>
        </form>
        
        <script>
    $(document).ready(function () {
        $("#kv-explorer").fileinput({
            //'theme': 'fas',
            'theme': 'explorer-fas',
            overwriteInitial: false,
            initialPreviewAsData: true,
            //uploadUrl: "/Upload",
            uploadAsync: false,
            maxFileCount: 5,
            //minFileCount: 2,

            maxFileSize: 80000,
            maxFilesNum: 10,

            allowedFileExtensions: ['jpg', 'png', 'gif'],
            //allowedFileTypes: ['image', 'video', 'flash'],

            //showUpload: false,
            //showRemove: false,
            //showPreview: false,
            //initialPreview: [
            //    "http://lorempixel.com/1920/1080/nature/1",
            //    "http://lorempixel.com/1920/1080/nature/2",
            //    "http://lorempixel.com/1920/1080/nature/3"
            //],
            //initialPreviewConfig: [
            //    {caption: "nature-1.jpg", size: 329892, width: "120px", url: "{$url}", key: 1},
            //    {caption: "nature-2.jpg", size: 872378, width: "120px", url: "{$url}", key: 2},
            //    {caption: "nature-3.jpg", size: 632762, width: "120px", url: "{$url}", key: 3}
            //]

            //uploadExtraData: {
            //    img_key: "1000",
            //    img_keywords: "happy, places",
            //}
            uploadExtraData: function () {
                return {
                    GalleryID: $("#GalleryID").val(),
                };
            }
        });
    });
</script>

You need to put all Css and js files in the first of the Upload.cshtml code. Then you need to set some initializer for it(script at the end of Upload.cshtml).

For the controller section, I suggest you use IFormFile.

public async Task<IActionResult> Upload(IEnumerable<IFormFile> files, string GalleryID /*same name with input name*/)
    {
        try
        {
            foreach (var item in files)
            {
                var UploadsRootFolder = Path.Combine(_env.WebRootPath, "GalleryFiles");
                if (!Directory.Exists(UploadsRootFolder))
                {
                    Directory.CreateDirectory(UploadsRootFolder);
                }
                if (item != null)
                {
                    string FileExtension = Path.GetExtension(item.FileName);
                    string NewFileName = string.Concat(Guid.NewGuid(), FileExtension);
                    string path = Path.Combine(UploadsRootFolder, NewFileName);

                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await item.CopyToAsync(stream);
                    }
                    CompressImage(NewFileName);
                }
            }
            
            return new JsonResult("success");
        }
        catch
        {
            return new EmptyResult();
        }
        
    }

This controller is for multiple files. If you want Ajax Upload you can use these codes in the script initializer(At the in the of Upload.cshtml).

uploadUrl: "/Upload",
//uploadAsync: false,

Use [Route("Upload")] for your Upload controller(uploadUrl in above and in Route["Upload"] must have same name)