Home > database >  upload file to wwwroot with ajax dot net 6 core
upload file to wwwroot with ajax dot net 6 core

Time:08-12

everyone!

I want to upload file to wwwroot/upload_files using ajax and .net For now I've successfully implemented the backend which is uploading file to location. But it is not working with ajax or maybe I'm not using the correct appoarch.

here is my view index.cshtml

<input type="file" id="files" name="files" />                                                

<input type="button"id="upload" value="Upload" />

ajax

        $("#upload").click(function (evt) {

            var fileUpload = $("#files");
            $.ajax({
                type: "POST",
                url: "/FilesController/UploadFile", //'https://localhost:7032/api/Files/UploadFile' and /Web/wwwroot/upload_files - but nothing works
                contentType: false,
                processData: false,
                data: data,
                success: function (message) {
                    alert(message);
                },

                error: function () {

                    alert("There was error uploading files!");

                }

            });

        });

controller

 [HttpPost("[action]")]
        public async Task<IActionResult> UploadFile(IFormFile files)
        {
            if (files == null || files.Length == 0)
                return BadRequest("file not selected");

          
            string rootPath = _appEnvironment.WebRootPath;

          
            string completePath = "";
            if (rootPath.Contains("RCSolution"))
            {
                // split the path till 
                completePath = rootPath.Substring(0, rootPath.IndexOf("Web"));
            }

            Console.WriteLine(completePath);
            string fullPath = completePath   "Web/wwwroot/upload_files/"   files.FileName;

            //string path = Path.Combine(fullPath);

            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                await files.CopyToAsync(stream);
            }


            //return RedirectToAction("Files");
            return Ok(files.FileName   " uploaded successfully "   "file location is "   fullPath);
        }

which is work fine as shown in this image

enter image description here

other apporach use from internet which does not works

https://codepedia.info/ajax-file-upload-aspnet-core-razor-pages#:~:text=Step to upload file in,a file on the server.

.NET Core 6 upload file to wwwroot/images fails sometimes and uploads half images

can anyone please help me how to deal with this issue? thanks

CodePudding user response:

you data that you are sending should be a formdata and you need to append file in that formdata object

var data = new FormData();
data.append("files", $('#files')[0].files[0]);

and you url should have format like "YourController/youraction" so after creating data object your ajaxcall will be same

$.ajax({
            type: "POST",
            url: "FilesController/UploadFile",
            contentType: false,
            processData: false,
            data: data,
            success: function (message) {
                alert(message);
            },

            error: function () {

                alert("There was error uploading files!");

            }

        });

CodePudding user response:

  $("#fileUpload").on('change', function () {

            target_url = api_url   "/api/Files/OnPostMyUploader";
            var files = $('#fileUpload').prop("files");
           
            formData = new FormData();
            formData.append("MyUploader", files[0]);

            jQuery.ajax({
                type: 'POST',
                url: target_url,
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                success: function (repo) {
                    if (repo.status == "success") {
                        alert("File : "   repo   " is uploaded successfully");
                    }
                },
                error: function () {
                    alert("Error occurs");
                }
            });
        });

      

this should work for me

thanks for all answers.

  • Related