Upload Image Asp net MVC

6

My question is this: imagine a scenario where I have a screen that has a form, and in this form there is also upload of images. Let's suppose I fill out the entire form, and select 3 images in input type file , when submitting, there in the controller I have the attributes of the completed form, and also the list of HttpPostedBaseFile with the 3 images inside,

  • It turns out that all other fields are populated again with values, but the images have been lost. The user must reselect the images.

    What is the best way to solve this? I wanted the images to come back too.

        
  • asked by anonymous 20.01.2016 / 05:30

    2 answers

    1
      

    What is the best way to solve this? I wanted the images to come back too.

    Using Backload . It is a package that manages a upload session of files in ASP.NET (can be MVC or Web Forms).

    An example using jQuery File Upload , taken from GitHub's own Backload:

    @using System.Web.Optimization
    
    @{
        ViewBag.Title = "Exemplo de Upload";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    @section styles {
        <!-- bootstrap styles -->
        <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    
        <!-- Styles for the jQquery File Upload Plugin in Basic Plus UI style -->
        @Styles.Render("~/backload/blueimp/bootstrap/BasicPlus/css")
    
        <!-- The main application styles -->
        <link href="~/Content/demo.styles.css" rel="stylesheet" />
    }
    
        <!-- Start of the render section -->
        <div class="container">
            <br>
            <blockquote>
                <p>
                    File Upload widget with multiple file selection, drag&amp;drop support, progress bar, validation and preview images, audio and video for jQuery. 
                    Supports cross-domain, chunked and resumable file uploads and client-side image resizing.
                </p>
            </blockquote>
            <br>
            <!-- The fileinput-button span is used to style the file input field as button -->
            <span class="btn btn-success fileinput-button">
                <i class="glyphicon glyphicon-plus"></i>
                <span>Add files...</span>
                <!-- The file input field used as target for the file upload widget -->
                <input id="fileupload" type="file" name="files[]" multiple>
            </span>
            <br>
            <br>
            <!-- The global progress bar -->
            <div id="progress" class="progress">
                <div class="progress-bar progress-bar-success"></div>
            </div>
            <!-- The container for the uploaded files -->
            <div id="files" class="files"></div>
            <br>
        </div>
        <!-- End of the render section -->
    
    
    @section scripts {
        <!-- Bootstrap script -->
        <script src="~/Scripts/bootstrap.min.js"></script>
    
        <!-- Scripts for the jQquery File Upload Plugin in Basic Plus UI style* -->
        @Scripts.Render("~/backload/blueimp/bootstrap/BasicPlus")
    
        <!-- The demo application script -->
        <script src="/Scripts/demos.blueimp.basicplus.js"></script>
    
    }
    

    The file demos.blueimp.basicplus.js contains the following (adapted and translated by me):

    /*jslint unparam: true */
    /*global window, $ */
    $(function () {
        'use strict';
    
        // O Backload é um produto freemium, então algumas funcionalidades são fechadas. 
        // O FileHandlerController é o controlador da sua sessão de upload.
        // No exemplo, definimos uma sessão de upload por um objectContext. 
        // Esse objectContext deve ser definido pela sua aplicação. No exemplo, 
        // foi definido com esse valor 'C5F260DD3787'. 
        var url = '/Backload/FileHandler?objectContext=C5F260DD3787';
    
        $('#fileupload').fileupload({
            url: url,
            dataType: 'json',
            autoUpload: false,
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test(window.navigator && navigator.userAgent),
            previewCrop: true,
            maxChunkSize: 10000000                                          // Opcional: tamanho de cada bloco de arquivo, em bytes, para facilitar uploads grandes.
        })
        .bind('fileuploadsubmit', function (e, data) {
            // Opcional: aqui geramos um uuid para identificar qual bloco de arquivo estamos enviando. O Backload reagrupa cada bloco de arquivo sozinho.
            data.formData = { uuid: Math.random().toString(36).substr(2, 8) };
        })
    
            // Aqui é a inicialização do tema Basic Plus do jQuery File Upload (https://blueimp.github.io/jQuery-File-Upload/basic-plus.html)
        .data('blueimp-fileupload').initTheme("BasicPlus");
    });
    

    If ModelState.IsValid is true , you can access the objectContext directory by using namespace System.IO classes, manipulate your files, and then delete the directory.

    The location of this directory can be set by configuration. My Web.Backload.config files are usually like this:

    <?xml version="1.0"?>
    <backload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="urn:backload-schema" xsi:noNamespaceSchemaLocation="Config\Web.Backload.xsd">
      <fileSystem filesRoot="~/Uploads/Temp" /> 
    </backload>
    
        
    11.09.2016 / 05:29
    0

    There is no way to recover files in the input file.

    But there are some 'contouring solutions'.
    One of the solutions is the use of 'simulation' of Ajax. Q: Why Ajax simulation? Home A: Simple, Ajax does not support sending files, so we simulate creating an invisible iframe (or flash, or silverlight for example) that receives a copy of the form and the responsibility of running the submit.

      

    There are several javascript plugins that do all this work for   you, in addition to providing a standardized API, such as jQuery   File upload .

    In this way you can keep the form data intact, since there was no page reload.
    Here is a small example of what it would be like to use jQuery File upload : p>

    $('#fileupload')
        .fileupload('send', {files: filesList})
        .success(function (result, textStatus, jqXHR) {
            console.log('Sucesso!');
            // Redireciona a página
            // ...
        })
        .error(function (jqXHR, textStatus, errorThrown) {
            console.error('Erro!');
            // trata os dados inválidos
            //...
        });
    

    jQuery File Upload

      

    PS: This is one of the solutions used to maintain backward compatibility with   browsers, since XHR2 already supports sending data   binaries.

        
    25.01.2016 / 07:06