0 votes

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

Good morning. I am 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 through js and send it to my server through AJAX as a parameter as 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 on the server side.

Greetings

0voto

First there are several things you need to 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 in charge of Selecting the file and calling 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: On the client it may look 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 may look 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);
            }
        }
    }

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X