1

I have an input element that selects an image as follows:

HTML Code

<input type="file"  id="uploadEditorImage"  />

Javascript Code

$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
    data.append("HelpSectionImages", files[0]);
}
$.ajax({
    url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
    type:"POST",
    processData: false,
    contentType: false,
    data: data,
    success: function (response) {
       //code after success

    },
    error: function (er) {
        alert(er);
    }

});

And Code in MVC controller

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
    {
        var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
    }

I want to save the selected image in a specific folder such as C\Temp. How can I go about doing that? Please help.

Thank you.

Alc
  • 35
  • 1
  • 6

1 Answers1

0

in your html:

 <input type="file" id="FileUpload1" />

script:

 $(document).ready(function () {
        $('#FileUpload1').change(function () {

            // Checking whether FormData is available in browser
            if (window.FormData !== undefined) {
                var data = new FormData();
                var files = $("#FileUpload1").get(0).files;
                console.log(files);
                if (files.length > 0) {
                    data.append("HelpSectionImages", files[0]);
                }
                $.ajax({
                    url: '/Home/UploadFiles',
                    type: "POST",
                    contentType: false, // Not to set any content header
                    processData: false, // Not to process data
                    data: data,
                    success: function (result) {
                        alert(result);
                    },
                    error: function (err) {
                        alert(err.statusText);
                    }
                });
            } else {
                alert("FormData is not supported.");
            }
        });
    });

and backend:

  [HttpPost]
    public ActionResult UploadFiles()
    {
        // Checking no of files injected in Request object  
        if (Request.Files.Count > 0)
        {
            try
            {
                //  Get all files from Request object  
                HttpFileCollectionBase files = Request.Files;
                for (int i = 0; i < files.Count; i++)
                {
                    //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";  
                    //string filename = Path.GetFileName(Request.Files[i].FileName);  

                    HttpPostedFileBase file = files[i];
                    string fname;

                    // Checking for Internet Explorer  
                    if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                    {
                        string[] testfiles = file.FileName.Split(new char[] { '\\' });
                        fname = testfiles[testfiles.Length - 1];
                    }
                    else
                    {
                        fname = file.FileName;
                    }

                    // Get the complete folder path and store the file inside it.  
                    fname = Path.Combine(Server.MapPath("~/Content/"), fname);
                    file.SaveAs(fname);
                }
                // Returns message that successfully uploaded  
                return Json("File Uploaded Successfully!");
            }
            catch (Exception ex)
            {
                return Json("Error occurred. Error details: " + ex.Message);
            }
        }
        else
        {
            return Json("No files selected.");
        }
    }
masoumeh miran
  • 180
  • 1
  • 9
  • Didn't work... I'm thinking the Url in the Javascript may need to be change as well. No? Thanks. – Alc Jun 23 '18 at 14:30
  • Still didn't work... Do I need to add a second button for saving? Thanks. – Alc Jul 06 '18 at 01:28
  • @Alc No !! you dont need because it hit function when you change file upload, but be careful your URL ( url: '/Home/UploadFiles',) is correct it is in home controller or if you want you can change it and you can use debugger for jquery and debug in your backend to see what is your problem. I tried it and it work successfuly. I'll hop do it successfully – masoumeh miran Jul 08 '18 at 05:25