Send file and text via jquery asp.net mvc

5

Personal I was able 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 do I 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
            });
        };
    
asked by anonymous 28.06.2016 / 01:14

3 answers

5

I think you're too complicated for something simple.

Just create a form and send the data to Ajax . An example would look 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 in order to make it as simple as possible.

The biggest difference is that I'm using the FormData () , which in a nutshell it uses the same format as a form would use if the encoding type was set to "multipart / form-data".

    
28.06.2016 / 22:09
3

According to the link documentation the basic usage is this:

Html:

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

Javascript:

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

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

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

What it generates:

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

The right thing is to create a FORM and throw everything inside it (if it does not already exist) and change the pointing 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 the Javascript:

$('#MEU_FORM').fileupload({
        type: 'POST',
        url: '@Url.Action("IMaterial","IDetailsArchives")',
        dataType: 'json',
        add: function (e, data) {
                jqXHRData = data
        },
    
28.06.2016 / 01:46
0

In the end it was as follows: I used what @Randrade passed me, but I increased it to be able to work the progress bar.

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

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

So I changed in my JS this:

'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
            })
        });

so:

$("#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 did not affect the progress bar percentage, that is, it goes to 100% with ease.

Follow all the 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>

    
29.06.2016 / 00:03