#

jQuery: 1-Button File-Upload mit Autostart, automatisches Upload von Dateien vom Browser zum Server

 

script Code

Dieses Beispiel zeigt, wie man in HTML, jQuery, javascript ein Foto-Upload erstellt, welche

·       Aus nur 1-Button besteht

·       Und automatisch nach der Auswahl mit dem Upload started.

 

Beispiel Ansicht:

FileUpload mit einfachem javascript, jQuery und HTML erstellt

 

Schritt 1

 

Mit diesem HTML,CSS Code erstellt man ein File-Upload Element, welches nur einen Button anzeigt

<form method="post" enctype="multipart/form-data">

    <input type="file" id="files_input_field" name="files" multiple class="inputfield_upload" onchange="upload_files();"/>

    <input type="button" id="select_and_upload_button" value="Upload Photos.." />

</form>

 

 

<style>

    .inputfield_upload {

        display: block;

        visibility: hidden;

        width: 0;

        height: 0;

    }

</style>

 

Ansicht:

Upload Photos Button eines Datei -Uploaders.

 

Schritt 2

Im script Block fügt man eine upload-function hinzu.

function upload_files() {..}

 

Diese Funktion wird gestarted, sobald im unsichtbaren Eingabeelement eine Änderung vorliegt.

Die Funktion wird im onchange-Event eingefügt in javascript-Schreibweise.

<input type="file" id="files_input_field" multiple class="inputfield_upload" onchange="upload_files();"/>

 

Der sichtbare Button führt beim eigenen Click-event einen Click auf dem unsichtbaren Upload-Element durch.

Der event-listener wird im jQuery-Block eingefügt.

$("#select_and_upload_button").click(function () { $("#files_input_field").click(); });

 

Vorgehensweise.

Sobald auf den Button: Select Photos geklickt wird, löst dieser den Dialog des File-Auswahl-Elementes aus.

Sobald dort eine Änderung onChange ausgelöst wird, kann diese die Funktion upload_files() ausführen.

 

 

Javascript und jQuery script Block

 

@*------------< jQuery-script >------------*@

<script type="text/javascript" src="~/lib/jquery/dist/jquery.js"></script>

<script>

    //----< events >----

    $("#select_and_upload_button").click(function () { $("#files_input_field").click(); });

   

 

    //--------< functions >--------

    function upload_files() {

        //------< upload_files() >------

        //--< get selected files >--

        var fileUpload = $("#files_input_field").get(0);

        var files = fileUpload.files;

        if (files.length == 0) return;

 

        //< load into FormData >

        var data = new FormData();

        for (var i = 0; i < files.length; i++) {

            data.append(files[i].name, files[i]);

        }

        //</ load into FormData >

        //--</ get selected files >--

 

        //--< ajax upload >--

        $.ajax({

            type: "POST",

            url: "Demo_02/Demo/UploadFilesAjax",

            contentType: false//default: 'application/x-www-form-urlencoded; charset=UTF-8'

            processData: false//default: data, other DOMDocument

            data: data,          //Type: PlainObject or String or Array

            //password:string    // HTTP access authentication

            //username:string    // HTTP access authentication

            success: function (message) {

                alert(message);

            },

            error: function () {

                alert("There was error uploading files!");

            }

        });

        //------</ upload_files() >------

    }

        //--------</ functions >--------

</script>

@*------------</ jQuery-script >------------*@

 

Die Dateien kommen aus einem Asp Net Core MVC Demo Projekt

 

Kompletter Code der asp.Net Core MVC Seite

 

@*------------< jQuery-script >------------*@

<script type="text/javascript" src="~/lib/jquery/dist/jquery.js"></script>

<script>

    //----< events >----

    $("#select_and_upload_button").click(function () { $("#files_input_field").click(); });

   

 

    //--------< functions >--------

    function upload_files() {

        //------< upload_files() >------

        //--< get selected files >--

        var fileUpload = $("#files_input_field").get(0);

        var files = fileUpload.files;

        if (files.length == 0) return;

 

        //< load into FormData >

        var data = new FormData();

        for (var i = 0; i < files.length; i++) {

            data.append(files[i].name, files[i]);

        }

        //</ load into FormData >

        //--</ get selected files >--

 

        //--< ajax upload >--

        $.ajax({

            type: "POST",

            url: "Demo_02/Demo/UploadFilesAjax",

            contentType: false//default: 'application/x-www-form-urlencoded; charset=UTF-8'

            processData: false//default: data, other DOMDocument

            data: data,          //Type: PlainObject or String or Array

            //password:string    // HTTP access authentication

            //username:string    // HTTP access authentication

            success: function (message) {

                alert(message);

            },

            error: function () {

                alert("There was error uploading files!");

            }

        });

        //------</ upload_files() >------

    }

        //--------</ functions >--------

</script>

@*------------</ jQuery-script >------------*@

 

 

Asp.Net Core MVC Controller

C#

Der asp Core MVC Controller nimmt die Dateien aus der ajax-Anfrage entgegen und speichert diese in einem User-Upload PFad

        [HttpPost]

        public async Task<IActionResult> UploadFilesAjax()

        {

            //< init >

            long uploaded_size = 0;

            string path_for_Uploaded_Files = _hostingEnvironment.WebRootPath + "\\User_Files\\_Upload_Folder\\";

            //</ init >

 

            //< get form_files >

            //IFormFile uploaded_File

            var uploaded_files = Request.Form.Files;

            //</ get form_files >

 

            //------< @Loop: Uploaded Files >------

            int iCounter = 0;

            string sFiles_uploaded = "";

            foreach (var uploaded_file in uploaded_files)

            {

                //----< Uploaded File >----

                iCounter++;

                uploaded_size += uploaded_file.Length;

                sFiles_uploaded += "\n" + uploaded_file.FileName;

 

                //< Filename >

                string  uploaded_Filename = uploaded_file.FileName;                

                string new_Filename_on_Server = path_for_Uploaded_Files + "\\" + uploaded_Filename;

                //</ Filename >

 

                //< Copy File to Target >

                using (FileStream stream = new FileStream(new_Filename_on_Server, FileMode.Create))

                {                   

                    await uploaded_file.CopyToAsync(stream);

                }

                //< Copy File to Target >

                //----</ Uploaded File >----

            }

            //------</ @Loop: Uploaded Files >------

 

 

            string message = "Upload successful!\n files uploaded:" + iCounter + "\nsize:" + uploaded_size  + "\n" + sFiles_uploaded ;

            return Json(message);

        }

 

Mobile

.

0123movie.net