ASP.net c# ajax image upload

03/01/2017 18:56 Hikarim#1
I have a issue with a image uploader i am making in ASP. I want to upload a image to the projects folder using ajax.

my html and js:

HTML Code:
   <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
    <a href="#" id="btnImg" onclick="uploadImg()" runat="server">UPLOAD</a>
    </div>
    </form>

<script>
    function uploadImg(){
        var formData = new FormData();
        formData.append('FileUpload1', $('#btnImg')[0].files[0]);
        $.ajax({
            type: "POST",
            url: 'Default.aspx/imageUpload',
            data: formData,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                alert(data);
            }
        });

    }
</script>
my image upload code(c#):

Code:
[WebMethod]
protected void imageUpload(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        Guid _fileNameRandom = Guid.NewGuid();
        string _fileNameStr = _fileNameRandom.ToString();
        FileUpload1.PostedFile.SaveAs(Server.MapPath("/Images/") + (_fileNameStr + fileName));
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}
IN console i get the following errors: Uncaught TypeError: Cannot read property '0' of undefined at uploadImg (Default.aspx:32) at HTMLAnchorElement.onclick (Default.aspx:21)

line 32 in default.aspx is: }); of the js script. and line 21 is: function uploadImg(){

Hope anyone can help me resolve this.
03/10/2017 17:58 ecks de#2
well. first of all u shouldn't upload the data directly into your project folder. this is a huge security gap and can get attacked quite easily. So you should add file validation. But however try this:
Code:
<asp:FileUpload ID="uploadIMG" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload Image" OnClick="Upload" />

protected void Upload(object sender, EventArgs e)
{
    if (uploadIMG.HasFile)
    {
        string fileName = Path.GetFileName(uploadIMG.PostedFile.FileName);
        uploadIMG.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
    }
}