Upload file ajax asp.net-mvc

2

I have the following problem when I use file upload. Ajax executes "at the same time" the two actions. And I would like him to perform the ulpoad action and then the other. Or 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;
    }
    
asked by anonymous 16.06.2014 / 20:16

1 answer

2

Test like this:

Where onreadystatechange == 4 : means: request is finished and response 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 some feedback:

Controller Index:

[HttpPost]        
public JsonResult Index(FormCollection form)
{
    HttpPostedFileBase file = Request.Files[0];
    return Json(new {Nome = "Nome do Arquivo"}, JsonRequestBehavior.AllowGet);
}
Ajax Javascript: Excerpt corresponding 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:

16.06.2014 / 20:35