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, wie man Fotos vom Browser auf einen Server hochlädt und die Ergebnisse anzeigt.

Dabei findet der Fileupload als ajax statt und die Ergebnisse werden als json mit jQuery in HTML eingefügt.

 

Upload von Fotos und Anzeigen in HTML

Mit dem Click auf den 1-Button File-Upload wird eine Dateidialog geöffnet, bei welchem man Fotos auswählen kann.

Sobald die Fotos ausgewählt sind, werden diese automatisch zum Server hochgeladen und anschliessend als Ergebnisse unterhalb des Upload-Buttons angezeigt.

 

Anzeige nach dem Upload.

Nach dem Hochladen werden die Fotos direkt als HTML Ergebnisse unterhalb des File-Upload Elements angezeigt.

Die Elemente werden als HTML Code asynchron nach dem Postback eingefügt.

 

 

Technik:

Client: Browser mit HTML, jQuery, javascript

Server: Asp.Net Core MVC

 

Erläuterung zum Einfügen des HTML Postbacks

Nachdem die Dateien zum Server hochgeladen wurden, sendet dieser ein Json Ergebnis zurück.

Dieses Json Struktur kann man in der success: oder done: Methode der jQuery.ajax function einstellen.

Dabei werden die json-Antwort als function( data ) übernommen.

Die auswertung erfolgt in einem jQuery.each durchlauf durch jedes Element mit

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

Dann wird für jedes Item Element ein HTML String erzeugt und diese mit jQuery an einen Div-Container als echte HTML-Childelemente eingefügt.

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

 

jQuery Code der Antwort-Daten

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 = "<br/><div style='width:200px'><img src='User_Files/_Upload_Folder/" + item + "' style='width:200px;'>" + item + "</div>";

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

                    //--</ Item >--

                })              

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

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

            },

 

 

 

 

View Code

File: Areas/Demo_02/Views/Demo/demo_02_Ajax_Image_Upload.cshtml

 

HTML, HTML5, jQuery, javascript, Razor-View

@{

    Layout = null;

}

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

 

<div id="divUploaded_Results"></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 >

        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

            //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 = "<br/><div style='width:200px'><img src='User_Files/_Upload_Folder/" + item + "' style='width:200px;'>" + item + "</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 >------------*@

 

 

 

Controller File

Areas/Demo_02/Controller/DemoController.cs

 

C# Code

Asp.Net Core MVC

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_02.Controllers

{

    [Area("Demo_02")]

    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: Ajax_Image_Upload

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

        public IActionResult demo_start()

        {

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

            return View("demo_02_Ajax_Image_Upload");

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

        }

 

        [HttpPost]

        public IActionResult ajax_Image_Upload_post(IFormCollection formFields)

        {

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

            //< out >

            return View("demo_02_Ajax_Image_Upload");

            //</ 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(sFiles_uploaded);

            return Json(list_Files);

        }

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

        #endregion

 

    }

}

 

 

 

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