Upload ajax file Asp.net-mvc

Asked

Viewed 914 times

2

I have the following problem when using file upload. ajax performs "at the same time" both actions. And I would like him to perform the ulpoad action and then the other. Or else another way to upload.

<div class="editor-field">
   <input type="file" name="file" id="file" />
   @Html.HiddenFor(model=>model.FotoVitrine)
   @Html.ValidationMessageFor(model => model.FotoVitrine)
</div>
<button type="button" onclick="postUpload('/CMS/Produto/Create', '/CMS/Produto/Index');" class="btn btn-success">Salvar</button>


function postUpload(post, redirect) {
    uploadfile();
    OpenPost(post, redirect);
}



function uploadfile() {
    var img = $("#file").val();
    if (img) {
        var file = document.getElementById('file').files[0];
        var formData = new FormData();
        formData.append(file.name, file);
        var xhr = new XMLHttpRequest();
        var url = "/Produto/UploadArquivo";
        xhr.open('POST', url, true);
        xhr.onload = function (e) {
            var response = $.parseJSON(e.target.response);
            console.log(response.fileName);
            alert(response.fileName);
            $("#FotoVitrine").val(response.fileName);
        };
        xhr.send(formData);
    }
}

    function OpenPost(url, redirect) {
        if ($("form").valid()) {
            var form = $("form").serialize();
            $('#Conteudo').empty().append('<div id="loader"><img src="/Content/Images/loading.gif"/></div>');
            $.ajax({
                type: "POST",
                url: url,
                data: form,
                success: function (response) {
                    Open(redirect);
                }
            });
        }
    }


    function Open(url, redirect) {
        $('#Conteudo').empty().append('<div id="loader"><img src="/Content/Images/loading.gif"/></div>');
        $.get(url, function (response) {
            if (redirect)
                Open(redirect);
            $('#Conteudo').html(response);
            $('#loader').remove();
        });
    }







    [AcceptVerbs(HttpVerbs.Post)]
    public void UploadArquivo()
    {
        HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;

        if (file != null && file.ContentLength > 0)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("server" + file.FileName);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("user", "pass");
            request.UsePassive = false;
            byte[] fileContents = new byte[file.ContentLength];
            file.InputStream.Position = 0;
            file.InputStream.Read(fileContents, 0, file.ContentLength);
            request.ContentLength = fileContents.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();
        }
    }


[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
    public PartialViewResult Create(FormCollection collection)
    {
        var bdprodutos = Loja_ProdutosAplicacaoConstrutor.Loja_ProdutosAplicacaoEF();
        var produto = new Loja_Produtos();
        produto.FotoVitrine = collection["FotoVitrine"];
        (...)
        return null;
    }

1 answer

2


Test like this:

Where onreadystatechange == 4: means: request is finished and the answer is ready and xhr.status == 200, process is "OK".

function postUpload(post, redirect) {
    uploadfile(post, redirect);    
}

function uploadfile(post, redirect) {
    var img = $("#file").val();
    if (img) {
        var file = document.getElementById('file').files[0];
        var formData = new FormData();
        formData.append(file.name, file);
        var xhr = new XMLHttpRequest();
        var url = "/Produto/UploadArquivo";
        xhr.open('POST', url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status==200) {
                OpenPost(post, redirect);
            }
        }
        xhr.onload = function (e) {
            var response = $.parseJSON(e.target.response);
            console.log(response.fileName);
            alert(response.fileName);
            $("#FotoVitrine").val(response.fileName);
        };
        xhr.send(formData);
    }
}

With feedback of some information:

Controler Index:

[HttpPost]        
public JsonResult Index(FormCollection form)
{
    HttpPostedFileBase file = Request.Files[0];
    return Json(new {Nome = "Nome do Arquivo"}, JsonRequestBehavior.AllowGet);
}

Ajax Javascript: Excerpt corresponds to the first example

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {         
        var dados = JSON.parse(xhr.responseText);
        alert(dados.Nome);
        OpenPost(post, redirect);
    }
}

Reference:

  • 1

    solved my problem. Giving an error now but not related to ajax, I’ll put the error here if you need to open another question: An Exception of type 'System.Net.Webexception' occurred in System.dll but was not handled in user code Additional information: The remote server returned an error: (425) Can’t open data Connection.

  • Better open another question! if the error is not in ajax

  • If my upload action returns a value (for example the renamed file name), how do I get it to ajax?

  • @Diegozanardo did the editing and put the example ...

Browser other questions tagged

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