Projekt-Anfragen: Tel: 07022/9319004 info@CodeDocu.de Software Entwicklung in C# WPF Asp.Net Core Vba Excel Word SQL-Server EF Linq, UWP Net
#

 

 

Dieses Beispiel zeigt eine Webseite, mit welcher man Dateien hochladen kann auf einen Server und dabei der aktuelle Übertragungsstatus angezeigt wird.

Das Beispiel enthält ein einfaches HTML Formular mit einem unsichtbaren Files-Input Element. Sobald die Dateien ausgewählt sind, startet der Upload automatisch.

Die Auswahl wird mit einem Button Upload Photos gestartet, welcher die Datei-Auswahl des File-Inputs öffnet.

 

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

    <input type="file" id="files_input_field" name="files"

           style="visibility:hidden;height:0px;width:0px;"

           onchange="upload_files();" />

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

</form>

 

 

Anschliessend startet die Auswahl die jQuery Function upload_files()

function upload_files() {..}

 

 

Die Dateien werden dabei einzeln hochgeladen.

# jQuery, Javascript, HTML, Asp MVC Core

 

 

Der Progressbar wird laufend erneuert durch eine xhr XMLhttpRequest Function in der ajax Upload-Funktion.

Hierbei wird ein EventListener gestartet, welcher auf den Upload-Progress reagiert.

xhr: function () {

    var xhr = new window.XMLHttpRequest();

    //Upload progress

    xhr.upload.addEventListener("progress", function (evt) {

        if (evt.lengthComputable) {

            var percentComplete = evt.loaded / evt.total;

            $("#ctlProgress").val(percentComplete * 100);

 

        }

    }, false);

    //Download progress

    xhr.addEventListener("progress", function (evt) {

        if (evt.lengthComputable) {

            var percentComplete = evt.loaded / evt.total;

            //Do something with download progress

            console.log(percentComplete);

        }

    }, false);

    return xhr;

},

 

Sobald die Function aufgerufen wird, wird der Wert im HTML Progress Element erneuert.

$("#ctlProgress").val(percentComplete * 100);

 

 

 

Komplette cshml Code-Datei

Client-script

 

Code in der Razor-View Datei, einfaches HTML

@{

    Layout = null;

}

<h2>Demo Upload with jQuery and Progress</h2>

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

    <input type="file" id="files_input_field" name="files" style="visibility:hidden;height:0px;width:0px;" onchange="upload_files();" />

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

</form>

 

<progress id="ctlProgress" value="0" max="100"></progress>

 

<div id="divUploaded_Results" style="display: flex;flex-flow:wrap;"></div>

 

 

 

 

@*------------< 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 >

 

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

            var data = new FormData();

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

            //</ load into FormData >

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

 

            //--< ajax upload >--

            $.ajax({

                type: "POST",

                url: "Demo_03/Demo/UploadFilesAjax",

                xhr: function () {

                    var xhr = new window.XMLHttpRequest();

                    //Upload progress

                    xhr.upload.addEventListener("progress", function (evt) {

                        if (evt.lengthComputable) {

                            var percentComplete = evt.loaded / evt.total;

                            $("#ctlProgress").val(percentComplete * 100);

 

                        }

                    }, false);

                    //Download progress

                    xhr.addEventListener("progress", function (evt) {

                        if (evt.lengthComputable) {

                            var percentComplete = evt.loaded / evt.total;

                            //Do something with download progress

                            console.log(percentComplete);

                        }

                    }, false);

                    return xhr;

                },

 

                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

                //jQuery 1.8 success->done error->fail

                success: function (data) {

                    //alert(data);

                    //console.log(data);

                    //---< show return >---

                    //--< Loop: each Result >--

                    $.each(data, function (index, item) {

                        //--< Item  >--

                        //*show uploaded Image in div-Results

                        var sItem = "<div ><img src='User_Files/_Upload_Folder/" + item + "' style='width:150px;'></div>";

                        $("#divUploaded_Results").append(sItem);

                        //--</ Item >--

                    })

                    //--</ Loop: each Result >--

                    //---</ show return >---

                },

                error: function () {

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

                }

            });

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

        }

 

    }

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

</script>

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

 

Server-seitiges script

Postback der Uploads

 

 

using Microsoft.AspNetCore.Mvc;

using IWois_Core.Data;              //ApplicationDbContext

using Microsoft.AspNetCore.Http;

using System.IO;

using Microsoft.AspNetCore.Hosting; //*IHostingEnvironment

using System.Threading.Tasks;       //Task

using System.Data;

using System.Collections.Generic;

 

namespace IWois_Core.Areas.Demo_03.Controllers

{

    [Area("Demo_03")]

    public class DemoController : Controller

    {

 

        #region Controller Init

        private readonly ApplicationDbContext _dbContext;

        private readonly IHostingEnvironment _hostingEnvironment;

 

       

        public DemoController(ApplicationDbContext dbContext, IHostingEnvironment hostingEnvironment)

        {

            //----< Init: Controller >----

            _dbContext = dbContext;

            _hostingEnvironment = hostingEnvironment;

            //----</ Init: Controller >----

        }

        #endregion

 

        #region Demo: demo_03_Upload_Progress

        //----------------< region Demo: Ajax_Image_Upload >-----------------

        public IActionResult demo_start()

        {

            //-------------< load StartView >-------------

            return View("demo_03_Upload_Progress");

            //-------------</ load StartView >-------------

        }

 

        [HttpPost]

        public IActionResult postback(IFormCollection formFields)

        {

            //-------------< demo_jQuery_01_post >-------------

            //< out >

            return View("demo_03_Upload_Progress");

            //</ out >

            //-------------</ demo_jQuery_01_post >-------------

        }

 

        [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 = "";

            List<string> list_Files = new List<string>();

            foreach (var uploaded_file in uploaded_files)

            {

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

                iCounter++;

                uploaded_size += uploaded_file.Length;

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

                list_Files.Add(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 >------

 

            return Json(list_Files);

        }

        //----------------</ region Demo: jQuery_Functions >-----------------

        #endregion

 

    }

}

 

 

 

 

Video Tutorial

https://www.youtube.com/watch?v=6ffsQkW0iGU

Mobile
»
Upload mit Progress Bar
»
jQuery: Wert einer HTML Progress Anzeige einstellen
»
Dateien hochladen und anzeigen mit jQuery ajax, FileUpload, Anzeigen des json Results
»
jQuery: 1-Button File-Upload mit Autostart
»
Dateien mit Ajax hochladen : Asp Net Core MVC und jQuery
»
jQuery: Function vor Submit Senden ausführen
»
jQuery: function nach dem Laden einer Seite ausführen
»
jQuery: HTML Elemente in ein Element einfügen
»
jQuery: Paste Event beim Einfügen von Text in ein HTML Element
»
jQuery: Insert event bei Text Eingabe

.

Jobs, Projekte, Angebote für Freiberufler, Selbstständig an Info@CodeDocu.de