Fieupload with Ajax.Beginform

Asked

Viewed 109 times

1

I’m having a problem, I need to update an image in the bank, 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.), as far as I have researched know that with Ajax.Beginform is not possible to upload, but what other way I could use to do this then ?

From now on I thank you all.

  • Good afternoon, did the answer solve your problem? If yes please mark it as "Correct". If not say what is missing. Thank you.

1 answer

2

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

Read how to use the File API: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

An example combining Ajax and Fileapi, using Drag and Drop (grab and drop the "file in the clipboard"):

<!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: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Uploading_a_user-selected_file

  • Thanks, I’ll try it

  • @Diegodias I wonder if the example helped you?

Browser other questions tagged

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