How do I get a file in JS and send it to ASP.net

0

Good day. I'm working with C # and ASP.Net on the server side and with JS and html on the client side.

I have a form similar to this

<form id='frmForm'>
<label>Subir Archivo</label>
<input type ='file' id='file' />
<button>Guardar</button>
</form>

What I want is to get the file using js and send it to my server through AJAX as a parameter, because I actually send several more fields.

If you could guide me on how to do this function, both on the client side and what type of data I receive from the server side

Greetings

    
asked by eezzekl 17.12.2016 в 22:56
source

1 answer

0

First there are several things you should do on the server: 1. Define a file type control like this     2. You must create a button that calls a JavaScript function that is responsible for    Select the file and call the Ajax function.    Try it 3. You must define the JavaScript function, something like this:           function LoadFile () {       var x = document.getElementById ("myFile");      }     4. In the function you must define the Ajax that communicates with the function on the server.

For example: In the client it can be something like this:

<script type="text/javascript">
        $(document).ready(function () {

            $('#btnUploadFile').on('click', function () {

                var data = new FormData();

                var files = $("#fileUpload").get(0).files;

                // Add the uploaded image content to the form data collection
                if (files.length > 0) {
                    data.append("UploadedImage", files[0]);
                }

                // Make Ajax request with the contentType = false, and procesDate = false
                var ajaxRequest = $.ajax({
                    type: "POST",
                    url: "UploadPage.aspx",
                    contentType: false,
                    processData: false,
                    data: data
                });

                ajaxRequest.done(function (xhr, textStatus) {
                    // Do other operation
                });
            });
        });
    </script>

On the server it can be something like this:

public partial class UploadPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
            if (httpPostedFile != null)
            {
                var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);

                // Save the uploaded file to "UploadedFiles" folder
                httpPostedFile.SaveAs(fileSavePath);
            }
        }
    }
    
answered by 18.12.2016 / 04:51
source