Send file and text via jquery Asp.net mvc

Asked

Viewed 1,530 times

6

Guys I managed to send the file through this code:

var jqXHRData = null;
        $(function () {
            $('.progress').progress({
                percent: 0
            });
            $("#divUpload").on('click', function () {
                $('#fu-my-simple-upload').click();
            });

            $("#hl-start-upload").on('click', function () {
                if (jqXHRData != null) {
                    if (jqXHRData) {
                        jqXHRData.submit();
                    }
                    return false;
                } else {
                    toastr.error("Selecione o arquivo, antes de enviar!", "Mensagem do Sistema");
                }
            });

            $("#fu-my-simple-upload").on('change', function () {
                $("#tbx-file-path").val(this.files[0].name); 
            });

            'use strict';

            $('#fu-my-simple-upload').fileupload({
            type: 'POST',
            url: '@Url.Action("IDetailsArchives", "IMaterial")',
            dataType: 'json',
            add: function (e, data) {
                    jqXHRData = data
            },
            done: function (event, data) {
                if (data.result.isUploaded) {
                    $("#tbx-file-path").val("Nenhum Arquivo Selecionado...");
                    toastr.success(data.result.message, "Mensagem do Sistema");
                }
                else {

                }
                jqXHRData = null;
                var intervalo = window.setInterval(progresso, 3000);
            },
            fail: function (event, data) {
                if (data.files[0].error) {
                    toastr.error(data.files[0].error, "Mensagem do Sistema");
                    var intervalo = window.setInterval(progresso, 3000);
                }
                jqXHRData = null;
            }
            }).on('fileuploadprogressall', function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('.progress').progress({
                    percent: progress
                })
            });
        });

        function progresso() {
            $('.progress').progress({
                percent: 0
            });
        };

Controller:

public virtual ActionResult IDetailsArchives(IArquivoMetadado arq)
        {
            HttpPostedFileBase myFile = Request.Files["MyFile"];
            bool isUploaded = false;
            string message = "Arquivo não enviado";

            if (myFile != null && myFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/App_Data/Arquivos");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        string FileNameNew = CriarNome(myFile.FileName, arq.conteudoID, arq.conteudoNome);
                        myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                        isUploaded = true;
                        message = "Arquivo enviado com sucesso!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("Arquivo não enviado: {0}", ex.Message);
                    }
                }
            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }

View:

<div class="ui grid">
<div class="fifteen wide column centered">
    <div class="ui grid">
        <div class="six wide column">
            <div class="ui fluid basic segment">
                <h4>Selecione o Arquivo: </h4>
                <div class="ui fluid action input">
                    <input type="hidden" id="conteudoID" name="conteudoID" value="@ViewBag.ID" />
                    <input type="hidden" id="conteudoNome" name="conteudoNome" value="@ViewBag.Nome" />
                    <input type="text" id="tbx-file-path" value="Nenhum Arquivo Selecionado..." readonly="readonly" />                        
                    @Html.TextBoxFor(m => m.MyFile, new { id = "fu-my-simple-upload", type = "file" , style = "display: none", accept = ".jpg, .png, .pdf, .doc, .docx" })
                    <div class="ui blue icon button" id="divUpload">
                        <i class="folder open outline icon"></i>
                    </div>
                </div>
                <br />
                <a id="hl-start-upload" class="ui right labeled blue icon button">
                    <i class="cloud upload icon"></i>
                    Enviar Arquivo
                </a>
                <div class="ui green progress">
                    <div class="bar">
                        <div class="progress"></div>
                    </div>
                </div>
                <h4>
                    Regras de Envio:<br />
                    • São aceitos somente os arquivos do formato: JPG, PNG, PDF, DOC e DOCX <br />
                    • A barra acima mostrar o progresso de envio do arquivo ao servidor.
                </h4>
            </div>
        </div>
        <div class="ten wide column">
            <div class="fifteen wide column centered">
                @Html.Action("IDetailsArchivesLista", "IMaterial", new { id = ViewBag.IDConteudo })
            </div>
        </div>
    </div>
</div>

but how to send other values along with my file? Type id, name and file? The id and name inputs will be Hidden

Update 1 JS Code:

var jqXHRData = null;
        $(function () {
            $('.progress').progress({
                percent: 0
            });
            $("#divUpload").on('click', function () {
                $('#MyFile').click();
            });

            $("#hl-start-upload").on('click', function () {
                if (jqXHRData != null) {
                    if (jqXHRData) {
                        $("#fileupload").submit();
                    }
                    return false;
                } else {
                    toastr.error("Selecione o arquivo, antes de enviar!", "Mensagem do Sistema");
                }
            });

            $("#MyFile").on('change', function () {
                $("#tbx-file-path").val(this.files[0].name); 
            });

            'use strict';

            $('#fileupload').fileupload({
            type: 'POST',
            url: '@Url.Action("IMaterial","IDetailsArchives")',
            dataType: 'json',
            add: function (e, data) {
                    jqXHRData = data
            },
            done: function (event, data) {
                if (data.result.isUploaded) {
                    $("#tbx-file-path").val("Nenhum Arquivo Selecionado...");
                    toastr.success(data.result.message, "Mensagem do Sistema");
                }
                else {

                }
                jqXHRData = null;
                var intervalo = window.setInterval(progresso, 3000);
            },
            fail: function (event, data) {
                if (data.files[0].error) {
                    toastr.error(data.files[0].error, "Mensagem do Sistema");
                    var intervalo = window.setInterval(progresso, 3000);
                }
                jqXHRData = null;
            }
            }).on('fileuploadprogressall', function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('.progress').progress({
                    percent: progress
                })
            });
        });

        function progresso() {
            $('.progress').progress({
                percent: 0
            });
        };

3 answers

5


I think you’re complicating something too simple.

Just create a form and send the data by Ajax. An example would be like this:

Model

public class IArquivoMetadado
    {
        public string conteudoID { get; set; }
        public string conteudoNome { get; set; }
        public string caminhoArquivo { get; set; }
        public HttpPostedFileBase MyFile { get; set; }
    }

View

@model jQueryUpload.Models.IArquivoMetadado

@{
    ViewBag.Title = "IDetailsArchives";
}

@using (Html.BeginForm("IDetailsArchives", "Home", FormMethod.Post, new { enctype = "multipart/form-data", @id = "form-id" }))
{
    <div class="jumbotron">
        <h1>ASP.NET Web API - File Upload</h1>
        <div class="row">
            <div class="col-md-12" style="font-size:medium">
                <div class="form-group">
                    <label class="col-md-2 control-label">Archivo:</label>
                    <div class="col-md-10">
                        <input type="hidden" id="conteudoID" name="conteudoID" value="2" />
                        <input type="hidden" id="conteudoNome" name="conteudoNome" value="3" />
                        @Html.TextBoxFor(m => m.MyFile, new { id = "fu-my-simple-upload", type = "file", accept = ".jpg, .png, .pdf, .doc, .docx" })
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Subir" class="btn btn-default" />
                    </div>
                </div>
            </div>
        </div>
    </div>
}



@section Scripts{
    <script>
        $("#form-id").submit(function () {

            var formData = new FormData($(this)[0]);

            $.ajax({
                url: window.location.pathname,
                type: 'POST',
                data: formData,
                success: function (data) {
                    alert(data)
                },
                cache: false,
                contentType: false,
                processData: false
            });

            return false;
        });
    </script>

}

Controller

 [HttpPost]
        public ActionResult IDetailsArchives(IArquivoMetadado arq)
        {
            bool isUploaded = false;
            string message = "Arquivo não enviado";

            if (arq.MyFile != null && arq.MyFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/App_Data/Arquivos");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        string FileNameNew = CriarNome(arq.MyFile.FileName, arq.conteudoID, arq.conteudoNome);
                        arq.MyFile.SaveAs(Path.Combine(pathForSaving, arq.MyFile.FileName));
                        isUploaded = true;
                        message = "Arquivo enviado com sucesso!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("Arquivo não enviado: {0}", ex.Message);
                    }
                }
            }
            return Json(new { isUploaded = isUploaded, message = message }, "text/html");
        }

I just changed your code to make it as simple as possible.

The biggest difference is that I’m using the Formdata(), that in summary it uses the same format that a form would use if the encoding type was set to "Multipart/form-data".

  • I advise to look at the code, and adapt it in the @Guilhermenascimento response, because I think you will want to add the progress bar and other information.

  • Could give an explanation, I personally understood, you used the Formdata, but I think it would be interesting to make it more evident ;)

  • 1

    @Guilhermenascimento Sometimes we do something so natural that we forget. Thanks for remembering. p

3

According to the documentation of https://blueimp.github.io/jQuery-File-Upload/ the basic use is this:

Html:

<form id="fileupload" action="exemplo" method="POST" enctype="multipart/form-data">
...

Javascript:

$('#fileupload').fileupload({
...

Namely the $('#fileupload').fileupload points to the <FORM>, but in case you pointed to the:

@Html.TextBoxFor(m => m.MyFile, new { id = "fu-my-simple-upload", type = "file" , style = "display: none", accept = ".jpg, .png, .pdf, .doc, .docx" })

That generates:

<input id="fu-my-simple-upload" type="file" />

The correct thing is to create a FORM and throw everything into it (if it no longer exists) and change the appointment ID, do something like:

<div class="ui fluid action input">
    <form id="MEU_FORM" action="[URL DE DESTINO, EDITE AQUI]" method="POST" enctype="multipart/form-data">
        <input type="hidden" id="conteudoID" name="conteudoID" value="@ViewBag.ID" />
        <input type="hidden" id="conteudoNome" name="conteudoNome" value="@ViewBag.Nome" />
        <input type="text" id="tbx-file-path" value="Nenhum Arquivo Selecionado..." readonly="readonly" />                        
        @Html.TextBoxFor(m => m.MyFile, new { id = "fu-my-simple-upload", type = "file" , style = "display: none", accept = ".jpg, .png, .pdf, .doc, .docx" })
        <div class="ui blue icon button" id="divUpload">
            <i class="folder open outline icon"></i>
        </div>
    </form>
</div>

And Javascript:

$('#MEU_FORM').fileupload({
        type: 'POST',
        url: '@Url.Action("IMaterial","IDetailsArchives")',
        dataType: 'json',
        add: function (e, data) {
                jqXHRData = data
        },
  • Right, but in case I have to insert the action there in the form and the url I pass in the fileupload what I do with it?

  • @Deividfarias the upload destination address. I think this is it @Url.Action("IDetailsArchives", "IMaterial")

0

At the end it was as follows: I used what @Randrade gave me, but I incremented it so I could run the bar.

I was using Jquery File Upload, but I was unable to send the two inputs that were hidden, so I removed Jquery File Upload and used Ajax to send the form.

The user @Guilhermenascimento tried to help me with Jquery File Upload, but even trying the way he put it did not get the positive result, which was to send the file and text in the same form.

So I changed in my JS that :

'use strict';

        $('#fu-my-simple-upload').fileupload({
        type: 'POST',
        url: '@Url.Action("IDetailsArchives", "IMaterial")',
        dataType: 'json',
        add: function (e, data) {
                jqXHRData = data
        },
        done: function (event, data) {
            if (data.result.isUploaded) {
                $("#tbx-file-path").val("Nenhum Arquivo Selecionado...");
                toastr.success(data.result.message, "Mensagem do Sistema");
            }
            else {

            }
            jqXHRData = null;
            var intervalo = window.setInterval(progresso, 3000);
        },
        fail: function (event, data) {
            if (data.files[0].error) {
                toastr.error(data.files[0].error, "Mensagem do Sistema");
                var intervalo = window.setInterval(progresso, 3000);
            }
            jqXHRData = null;
        }
        }).on('fileuploadprogressall', function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('.progress').progress({
                percent: progress
            })
        });

therefore:

$("#form-id").submit(function () {
            var formData = new FormData($(this)[0]);

            $.ajax({
                url: '@Url.Action("IDetailsArchives","IMaterial")',
                type: 'POST',
                data: formData,
                async: true,
                success: function (data) {
                    $("#tbx-file-path").val("Nenhum Arquivo Selecionado...");
                    toastr.success(data.message, "Mensagem do Sistema");
                    var intervalo = window.setInterval(progresso, 3000);
                },
                error: function (data) {
                    toastr.error(data.message, "Mensagem do Sistema");
                        var intervalo = window.setInterval(progresso, 3000);
                },
                cache: false,
                contentType: false,
                processData: false,
                xhr: function () {
                    myXhr = $.ajaxSettings.xhr();
                    if (myXhr.upload) {
                        myXhr.upload.addEventListener('progress', showProgress, false);
                    } else {
                        console.log("Uploadress is not supported.");
                    }
                    return myXhr;
                }
            });

            return false;
        });

Remembering that small files have not affected the percentage of the bar Progress, ie, goes to 100% with ease.

Follows all functional code:

Controller:

[HttpPost]
        public virtual ActionResult IDetailsArchives(IArquivoMetadado arq)
        {
            HttpPostedFileBase myFile = Request.Files["MyFile"];
            bool isUploaded = false;
            string message = "Arquivo não enviado";

            if (myFile != null && myFile.ContentLength != 0)
            {
                string pathForSaving = Server.MapPath("~/App_Data/Arquivos");
                if (this.CreateFolderIfNeeded(pathForSaving))
                {
                    try
                    {
                        string arquivoAtual = myFile.FileName.Split('.').First();
                        string tipoAtual = myFile.FileName.Split('.').Last();
                        string FileNameNew = CriarNome(arquivoAtual, arq.conteudoNome, arq.conteudoID, tipoAtual);
                        myFile.SaveAs(Path.Combine(pathForSaving, FileNameNew));
                        isUploaded = true;
                        message = "Arquivo enviado com sucesso!";
                    }
                    catch (Exception ex)
                    {
                        message = string.Format("Arquivo não enviado: {0}", ex.Message);
                    }
                }
            }
            return Json(new { message = message }, "text/html");
        }

        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    /*TODO: You must process this exception.*/
                    result = false;
                }
            }
            return result;
        }

        private string CriarNome(string nomeAtual, string conteudoNome, string idcont, string tipo)
        {
            string data = DateTime.Now.ToString("dd-mm-yyyy");
            novoNome = "" + conteudoNome + "-" + nomeAtual + "-" + idcont + "-" + data + "."+tipo;
            return novoNome;
        }

HTML/JS :

@section Scripts{
       
        var jqXHRData = null;
        $(function () {
            $('.progress').progress({
                percent: 0
            });
            $("#divUpload").on('click', function () {
                $('#MyFile').click();
            });

            $("#hl-start-upload").on('click', function () {
                var arquivo = $("#MyFile").val();
                if (arquivo == "") {
                    toastr.error("Selecione o arquivo, antes de enviar!", "Mensagem do Sistema");
                }
                else
                    $("#form-id").submit();
            });

            $("#MyFile").on('change', function () {
                $("#tbx-file-path").val(this.files[0].name); 
            });

            $("#form-id").submit(function () {
                var formData = new FormData($(this)[0]);

                $.ajax({
                    url: '@Url.Action("IDetailsArchives","IMaterial")',
                    type: 'POST',
                    data: formData,
                    async: true,
                    success: function (data) {
                        $("#tbx-file-path").val("Nenhum Arquivo Selecionado...");
                        toastr.success(data.message, "Mensagem do Sistema");
                        var intervalo = window.setInterval(progresso, 3000);
                    },
                    error: function (data) {
                        toastr.error(data.message, "Mensagem do Sistema");
                            var intervalo = window.setInterval(progresso, 3000);
                    },
                    cache: false,
                    contentType: false,
                    processData: false,
                    xhr: function () {
                        myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) {
                            myXhr.upload.addEventListener('progress', showProgress, false);
                        } else {
                            console.log("Uploadress is not supported.");
                        }
                        return myXhr;
                    }
                });

                return false;
            });
        });

           function showProgress(evt) {
               if (evt.lengthComputable) {
                   var percentComplete = (evt.loaded / evt.total) * 100;
                   $('.progress').progress({
                       percent: percentComplete
                   })
               }
           }

        function progresso() {
            $('.progress').progress({
                percent: 0
            });
        };
    
}
<div class="ui grid">
<div class="fifteen wide column centered">
    <div class="ui grid">
        <div class="six wide column">
            <div class="ui fluid basic segment">
                <h4>Selecione o Arquivo: </h4>
                <div class="ui fluid action input">
                    @using (Html.BeginForm("IDetailsArchives", "IMaterial", FormMethod.Post, new { enctype = "multipart/form-data", @id = "form-id" }))
                    {
                        <input type="hidden" id="conteudoID" name="conteudoID" value="@ViewBag.ID" />
                        <input type="hidden" id="conteudoNome" name="conteudoNome" value="@ViewBag.Nome" />
                        <input type="text" id="tbx-file-path" value="Nenhum Arquivo Selecionado..." readonly="readonly" />
                        @Html.TextBoxFor(m => m.MyFile, new { id = "MyFile", type = "file", style = "display: none", accept = ".jpg, .png, .pdf, .doc, .docx" })
                        <div class="ui blue icon button" id="divUpload">
                            <i class="folder open outline icon"></i>
                        </div>
                    }
                </div>
                <br />
                <a id="hl-start-upload" class="ui right labeled blue icon button">
                    <i class="cloud upload icon"></i>
                    Enviar Arquivo
                </a>
                <div class="ui green progress">
                    <div class="bar">
                        <div class="progress"></div>
                    </div>
                </div>
                <h4>
                    Regras de Envio:<br />
                    • São aceitos somente os arquivos do formato: JPG, PNG, PDF, DOC e DOCX <br />
                    • A barra acima mostrar o progresso de envio do arquivo ao servidor.
                </h4>
            </div>
        </div>
        <div class="ten wide column">
            <div class="fifteen wide column centered">
                @Html.Action("IDetailsArchivesLista", "IMaterial", new { id = ViewBag.IDConteudo })
            </div>
        </div>
    </div>
</div>

  • Could explain what was wrong and what you had to do to make it work, make the answer relevant to future visitors who might have the same kind of difficulty ;)

Browser other questions tagged

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