0

This form i want to send using ajax call with file, but it is not calling the c# function and not showing any error.

//form to submit
<form id="formfile" enctype="multipart/form-data">
    <div class="modal-body">
       <input type="file" id="fileupload1"/>
    </div>
    <div class="modal-footer">
        <input type="submit" id="savefiles" class="buttonType" onclick="saveFile();return false" value="Save File" /> 
    </div>
</form>

This ajax call is used to call c# code and also send file(.pdf)

//ajax call in .aspx file
function saveFile() {
    debugger;
    var file = $('input[type="file"]').val();
    var exts = ['pdf', 'PDF'];

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

    if (file) {

        var extension = file.substring(file.lastIndexOf('.') + 1, file.length);

        if ($.inArray(extension, exts) > -1)
        {
            //var formData = new FormData($('#form1')[0]);
            var fileUpload = $('#fileupload1').get(0);
            var files = fileUpload.files;  


            for (var i = 0; i < files.length; i++) {
                formData.append(files[i].name, files[i]);
            }
            formData.append(fileUpload.name, fileUpload);
            //alert('File Uploaded Successfully!');
        }

        else
        {
            alert('Invalid file, Only pdf files can be uploaded!!!');
        }
    }
    //var str = "abc";
    $.ajax({
        url: "FileUploader.aspx/savepdfFiles",
        type: "POST",
        //cache: false,
        contentType: false,
        processData: false,
        data: formData,
        success: function (data) {
            debugger;

        },
        error: function (data) {
            debugger
        }
    });
}

It will come into success section also, but not calling following method.

//c# code
[webMethod]
public static void savepdfFiles()
{ 
   //code
}

In ajax call it goes into success. but not calling savepdfFiles() method.

7
  • 1
    have a look, what function name you written to call <input type="submit" id="savefiles" class="buttonType" onclick="SaveFileToTemp();return false" value="Save File" /> and what is your function name. Commented Aug 23, 2016 at 13:45
  • sorry, actually I was trying the code that's why, but on submit it will call that method. Commented Aug 23, 2016 at 13:52
  • The main problem is that it is not calling C# method. Commented Aug 23, 2016 at 13:55
  • Can you call any other C# method? the server could be sending a response that is interpreted as success, but not allowing the method to execute... check your app configuration on your server. Commented Aug 23, 2016 at 14:11
  • yep, I am calling the same method with no data or string data, it's working fine. But for PDF(or file), there is some problem. Commented Aug 23, 2016 at 14:14

2 Answers 2

1

EDIT 24/08/2016

You can convert your blob data to base 64 and send it in JSON

var filesLength = 0;
function SaveFileToTemp() {

    var file = $('input[type="file"]').val();
    var exts = ['pdf', 'PDF'];

    var pdfList = [];
    // var pdfFile = { FileName: '', B64Data: '' };

    if (file) {

        var extension = file.substring(file.lastIndexOf('.') + 1, file.length);

        if ($.inArray(extension, exts) > -1) {

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

            filesLength = files.length;
            for (var i = 0; i < files.length; i++) {
                var reader = new window.FileReader();
                reader.myFileIndex = i;
                reader.onloadend = function () {
                    base64data = reader.result;
                    pdfList.push({ FileName: files[this.myFileIndex].name, B64Data: base64data.substr(base64data.indexOf(',') + 1) });
                    console.log(base64data);
                    filesLength--;
                    if (filesLength === 0) {
                        $.ajax({
                            url: "/FileUploader.aspx/savepdfFiles",
                            type: "POST",
                            //cache: false,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            data: JSON.stringify({ listPdf: pdfList }),
                            success: function (data) {
                                //alert('File Uploaded Successfully!');
                                debugger;
                            },
                            error: function (data) {
                                debugger
                            }
                        });
                    }
                }
                reader.readAsDataURL(files[i]);
            }
        }

        else {
            alert('Invalid file, Only pdf files can be uploaded!!!');
        }
    }          


}

and in C#

[WebMethod]
public static void savepdfFiles(List<PdfFile> listPdf)
{
    //code
    foreach (var item in listPdf)
    {
        byte[] data = Convert.FromBase64String(item.B64Data);
        System.IO.File.WriteAllBytes(string.Format("d:\\temp\\{0}",item.FileName), data) ;
    }

}

this is my clas PdfFile for info

public class PdfFile
{
    public string FileName { get; set; }
    public string B64Data { get; set; }
}

Maybe you have to add this to your web.config to allow big json serialization :

 <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="10240000"/>
      </webServices>
    </scripting>
  </system.web.extensions>

You have to set the appropiate value for maxJsonLength

Previous answer

I think I had this problem before from what i remember there is mechanism that doesn't allow you to this.

Maybe I'm wrong but I share you a link. You will have to handle this with an ashx.

here is a built-in validation layer of protection that ASP.NET enforces for both GET and POST based ASP.NET AJAX web methods, which is that regardless of the HTTP verb being used, ASP.NET always requires that the HTTP Content-Type header is set to the value application/json. It this content type header is not sent, ASP.NET AJAX will reject the request on the server.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, using .ashx it is working fine, but we want it in same page only.
So if I'm right you can't use content-type=application/x-www-form-urlencoded, or multipart/form-data
0

I know this problem and it's easy to solve just you have to use Generic Handler. Using generic handler with your AJAX call you can send any file to asp.net C# function. In Generic Handler you have to write following c# code.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace UploadFile
{
/// <summary>
/// Summary description for UploadFileHandler
/// </summary>
public class UploadFileHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        if (context.Request.Files.Count > 0)
        {
            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                string fname;
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = file.FileName;
                }
                fname = Path.Combine(context.Server.MapPath("~/Uploads/"), fname);
                file.SaveAs(fname);
            }
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write("File Uploaded Successfully!");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
}

Here is the example...

If you want Full Example Click here!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.