Assigning an image(s) value to the Javascript input

Asked

Viewed 779 times

2

I have the following input

<input type="file" id="imagefiles" name="files[]" multiple accept="image/*" style="display:none;" />

This input receives up to 3 images

I’m using javascript to give a post this way 'Imagem': $('#imagefiles').val(), but in this case it only takes the first image, as I am using files[] I would like to know how to access the 3 vector positions and assign in javascript.

Agradicmento @Magichat for having helped me in the past issue, made available the code to upload the images , follows the code I am using :

 var fileSelect = document.getElementById("fileSelect");
var fileElem = document.getElementById("imagefiles");



fileSelect.addEventListener("click", function (e) {
    fileSelect.style.cssFloat = "top";
    fileSelect.style.marginRight = "10px";
    fileSelect.style.marginTop = "-3px";
    if (fileElem) {
        fileElem.click();
    }
    e.preventDefault();
}
, false);

function handleFileSelect(evt) {

    var list = document.getElementById("list").childElementCount;
    var files = evt.target.files;
    var qtde = files.length;
    var nomes = fileElem.files;
    var nome;

    if (qtde > 3 || list > 2) {
        alert('Erro! Número máximo de fotos é 3 !');
        document.getElementById('imagefiles').value = "";
        return;
    } else {
        for (var i = 0, f; f = files[i]; i++) {
            if (!f.type.match('image.*')) {
                continue;
            }
            var reader = new FileReader();
            reader.onload = (function (theFile) {
                return function (e) {
                    var span = document.createElement('span');
                    span.innerHTML =
'<div class="col-lg-4">' + "<a href='#'><img style='float:left;padding: 1px;height: 155px; margin-right:15px; width: 155px;border: 5px solid #c7c7c7;margin-top: 0px;' src='" + e.target.result + "'" + "title='" + escape(theFile.name) + "'/>" + '<img src="/Content/imagens/principais/close-button.png" style="height: 15px; width: 15px; margin-right:5px;">' + "  </a></div>";
                    document.getElementById('list').insertBefore(span, null);
                    span.children[0].addEventListener("click", function (evt) {
                        span.parentNode.removeChild(span);
                    });
                };
            })(f);
            reader.readAsDataURL(f);
        }
        return true;
    }
}
document.getElementById('imagefiles').addEventListener('change', handleFileSelect, false);

EDIT : the complete part of the input :

<legend class="leg_img">Insira imagens</legend>
                <fieldset id="upload_img" class="nf_class upload_img">
                    <input type="file" id="imagefiles" name="files[]" multiple accept="image/*" style="display:none;" />
                    <a href="#" id="fileSelect" class="btn btn-success" style="margin-bottom:10px">selecionar imagens</a>
                    <div id="list" style="margin-bottom:0;"></div>
                </fieldset>

EDIT 2 : Post :

 $('#btnSubmit').click(function () {
    NovaPublicacao();
})

function NovaPublicacao() {
    var produtoData = {

        'Titulo': $('#produtoTitulo').val(),
        'Descricao': $('#produtoDescricao').val(),
        'Imagem': $('#imagefiles').val()

        // adicionando valores as variáveis
    };
    console.log(produtoData);

    $("#disableModal").addClass("disabledbutton"), // disabilita a pagina
    $('#loadingModal').show(); // Adiciona o Loading
    $.ajax({
        url: "/Produto/Publicar", //altere para o caminho que você vai querer mandar o post
        type: "post", //tipo post
        data: produtoData, //os dados
        success: function (json) { //em caso de  sucesso faça
            if (json.isRedirect) {
                window.location.href = json.redirectUrl;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {//em caso de erro faça
            console.log(textStatus, errorThrown);
        }
    });
}

EDIT 3 : I will explain a little of the situation of the Backend, these methods I did not do, but as they do not serve but for the model of the Administrator, because they climbed only 1 photo, I will have to change it, but still do not know how to pass the information needed for it, so I haven’t even altered it yet .

  public JsonResult CriarPublica(string ProdutoId, HttpPostedFileBase uploadFile)
    {
        if (Web.Utils.Util.ExtensaoPermitidaImagem(Path.GetExtension(uploadFile.FileName.ToLower())))
        {
            int idProduto = Convert.ToInt32(SystemCriptografia.ToDescriptografaQueryString(ProdutoId));
            var produto = ProdutoServico.GetById(idProduto);
            if (produto == null)
                return Json(new { Erro = true, Msg = ConfigurationManager.AppSettings["MSG_ERRO_DADOS"] });
            int qntofotos = this.FotoProdutoServico.GetMany(p => p.ProdutoId == idProduto).Count();
            if (qntofotos == produto.Loja.QntMaxFotosProduto)
            {
                return Json(new { Erro = true, Msg = ConfigurationManager.AppSettings["MSG_NUMERO_MAXIMO_FOTOS"] });
            }

            string NomeImagem = uploadFile.FileName.ToLower();
            string ExtensaoImagem = Path.GetExtension(uploadFile.FileName.ToLower());
            FotoProduto foto = new FotoProduto(idProduto, NomeImagem, ExtensaoImagem);

            this.FotoProdutoServico.Add(foto);

            int dimensao = Convert.ToInt32(ConfigurationManager.AppSettings["TAMANHO_FOTO_PRODUTO"]);
            Image i = Image.FromStream(new MemoryStream(Web.Utils.Util.RedimensionarImagem(uploadFile.InputStream, dimensao)));
            ProdutoServico.SalvarArquivoProduto(i, foto);

            //-----INSERÇÃO NO MODELO ANTIGO!
            produto.NomeImagem = produto.ProdutoId.ToString();
            produto.Extensao = ExtensaoImagem;
            this.ProdutoServico.Update(produto);

            Image f = Image.FromStream(new MemoryStream(Web.Utils.Util.RedimensionarImagem(uploadFile.InputStream, dimensao)));
            ProdutoServico.SalvarArquivos(i, produto);
            //-----------------------


            return Json(new { Atualizar = true, Msg = ConfigurationManager.AppSettings["MSG_IMG_ENVIADA"] });
        }
        else
        {
            return Json(new { Erro = true, Msg = ConfigurationManager.AppSettings["MSG_ERRO_EXTENSAO_IMAGEM"] });
        }
    }

}

OBS. Actually there is one more way I’m still analyzing these backend methods, maybe I will change them altogether.

  • Put the POST part in your code, what you’re trying to.

  • Ours nor noticed that had not put the full part , a second.

  • How do you feel about changing the term "vector" to "image(s)"?

  • 1

    I switched if you think it looks better... =] ...

  • You can also show the code next to the server, for sure we will need to modify it

  • 1

    I will post yes, but I don’t have so much difficulty with this part, the problem is that when I try to send the code to the controller ( I’m doing in c#) the 'picture' field only gets an image, and I would like to have the three separate. I’ll post the cider here.

  • @Williamcézar I understand... it seems that in your code in C# you do not access the parameters of the URL, it was even easier with a function like this

Show 2 more comments

3 answers

1


I didn’t test it, see if it helps...

function NovaPublicacao() {

    var elem = document.getElementById("imagefiles");
    var images = [];
    for (var i = 0; i < elem.files.length; ++ i) {
       images.push(elem.files[i].name);
    }
    var produtoData = {

        'Titulo': $('#produtoTitulo').val(),
        'Descricao': $('#produtoDescricao').val(),
        'Imagem': images[];
};
  • Your method worked right , thank you very much

  • only thing now and I am not getting to pass as Json , I added , I asked a new question , sorry the amount of question more this and all very new and I need to finish this work , you helped a lot my understanding on the function. http://answall.com/questions/152784/jquery-n%C3%A3o-passa-informa%C3%A7%C3%A3o-para-o-controller

1

So you want to pass multiple images to the URL? In addition to doing this, you’ll need to go through each one in the code next to the server.

One way to do this is to create parameters in the URL (or POST) with a preset at the beginning of the name, for example:

?Image0=&Image1=

And so we can save the data of each image in a parameter that starts with the "Image" preset, with some number or name in front, always different from the previous one.

Now here’s an example of implementation in your code:

(Client-side)

/* cria o parâmetro de cada imagem */
for (var i = 0, files = $("#imagefiles")[0].files, f; f = files[i++];) {
    var reader = new FileReader
    reader.onload = function() {
        /**
         * this.result contém o conteúdo binário da imagem
         * criptografado com base64, com um
         * cabeçalho extra usado em URLs.
         */
        produtoData["Image" + i] = encodeURIComponent(this.result);
    }
    reader.readAsDataURL(f)
}

(Server-side)

I don’t understand how C# works to capture URL parameters, in fact I never used C# next to the server. This is an example in PHP that can be easily converted to C#.

<?php

/* atravessa cada parâmetro no URL */
foreach ($_POST as $url_param) {

    /* checa se começa o parâmetro começa com "Image" */
    if (substr($url_param, 0, 5) === "Image")

        /* possíveis dados */

        /* $_POST['Titulo'], $_POST['Descricao'], $url_param) */
}
  • I’m analyzing your code here , I’ll be back soon , but anyway thank you.

  • @Williamcézar Note: Javascript code would be entered before calling jQuery.ajax, for the object produtoData would have been modified before being sent there. Re-check the client-side code, there was a typo.

  • I’m researching some C# methods to give you an example of the server-side in C#

  • 1

    In case this ajax method calls the Product/Publish controller la if the parameters are with the same name I can already use them in the controller , I’m seeing your code and seeing what I should do, but I’m with some difficulty, already I put my doubts , but very compelled by the attention

  • I will try to explain the situation , when I post I pass a JSON to the controller I put in Ajax. but my problem is using make an image array , or simply put 3 images in 3 diverging variables> type Imagem1 = files[0] imagem2 = files[1] Because then I declare the same names in my controller and I can save it in the bank.

  • The @Magichat method Solved , is now sending an array with the string with the image , now and only handle in the backend , thank you very much for your help .

  • @Williamcézar I found a method in C# now, but I thought you wanted the binary content of the image. You’re passing the file name, not the content of the image... I didn’t know it was to get the name :p

  • To get the image file name just index its object with "name"

Show 3 more comments

1

the method .val() jQuery only returns information about the first Arrays item.

The input file contains the property files of the kind FileList, containing the information of the selected images.

Itere on this property to fill the produtoData from the POST, and call $.ajax with options to apply the processing standards upon the produtoData when sending the request:

var imageFiles = document.getElementById('imagefiles');

var produtoData = new FormData();

var files = document.getElementById('imagefiles').files;
for (var i = 0; i < files.length; i++) {
  produtoData.append('Imagem['+i+']', files[i]);
}

$.ajax({
  ...,
  processData: false,    // Não transforma ajaxData
  contentType: false,
  ...
});
  • I’m having trouble sending the information with post , first because I was without processData and contentData, and that you use a different way of iterating the array, if you can answer this question : http://answall.com/questions/152784/jquery-n%C3%A3o-pass-informs%C3%A7%C3%A3o-to-the-controller

Browser other questions tagged

You are not signed in. Login or sign up in order to post.