FieUpload with Ajax.BeginForm

1

I have a problem, I need to update an image in the database, I'm sending this image with a fileUpload, and I have an Ajax.BeginForm (because I use the ajax call to create tabs on my page.), where I know that with Ajax.BeginForm it is not possible to upload, but what other way could I use it to do it then?

Thanks in advance.

    
asked by anonymous 18.12.2014 / 17:41

1 answer

2

It is not a "problem" with Ajax.BeginForm , the issue is that you can not upload with XMLHttpRequest (ajax), for this you will need File API (javascript).

Read how to use the File API: link

An example combining AJAX and FileAPI, using Drag and Drop (get and drop the "file in the transfer area"):

<!DOCTYPE html>
<html>
<head>
    <title>dnd binary upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        function sendFile(file) {
            var uri = "/index.aspx";
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    //Resposta do servidor
                    console.log(xhr.responseText);
                }
            };
            fd.append('myFile', file);//myFile é a variavel requisitada para o servidor
            // Inicia o upload multipart/form-data
            xhr.send(fd);
        }

        window.onload = function() {
            var dropzone = document.getElementById("dropzone");
            dropzone.ondragover = dropzone.ondragenter = function(event) {
                event.stopPropagation();
                event.preventDefault();
            }

            dropzone.ondrop = function(event) {
                event.stopPropagation();
                event.preventDefault();

                var filesArray = event.dataTransfer.files;
                for (var i=0; i<filesArray.length; i++) {
                    sendFile(filesArray[i]);
                }
            }
        }
    </script>
</head>
<body>
    <div>
        <div id="dropzone">Drag & drop o seu arquivo aqui</div>
    </div>
</body>
</html>

Source: link

    
18.12.2014 / 17:50