0

I'm having an issue trying to post a file to an ASP.Net WebMethod, and return some JSON. The primary problem is that I don't know what to set the contentType of the AJAX post in order to both be able to send the file and receive back JSON. If the contentType is "application/json; charset=utf-8", then I receive this error.

{"Message":"Invalid JSON primitive: ------WebKitFormBoundary1HaBThatcuXovAC2.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

If I set the contentType to null, then I'll get past this error, and the request will properly post the file, but I end up receiving the entire page back as a response.

This was a similar situation, but they weren't trying to post a file. Jquery AJAX with ASP.NET WebMethod Returning Entire Page

Is there some way for me to get around this? I don't know if/how I could change the content type from the backend of the page to only return the json, or if there is a way to include the file as part of the post with conentType not set to null. I've been struggling with this for a while. Any help would be appreciated. Thanks.

jQuery

function UploadFile() {
$('.uploadButton').click(function () {
    var projectID = $(".projectID").val();
    var imageUploader = document.getElementById("imageFile");    
    var files = imageUploader.files;
    var file = imageUploader.files[0];
    name = file.name;
    size = file.size;
    type = file.type;
    if (window.FormData !== undefined) {
        var data = new FormData();
        for (var x = 0; x < files.length; x++) {
            data.append(files[x].name, files[x]);
        }
        data.append("description", $(".fileDescription").val());
        data.append("projectID", projectID);
    }
        $.ajax({
            //url: 'ajax.aspx/UploadImage?projectID=' + projectID + '&description=' + $(".description").val(),
            url: 'ajax.aspx/UploadImage',
            type: 'POST',
            data: data,
            cache: false,
            contentType: "application/json; charset=utf-8",
            //contentType: false,
            processData: false,
            dataType: 'json',
            success: completeHandler = function (msg) {
                console.log(msg);
                console.log(msg.d);
                var documentInfo = JSON.parse(msg.d);

            },
            error: errorHandler = function (e) {
                console.log(JSON.stringify(e));
                alert(e);
            }
        });
});
}

ajax.aspx.cs

  protected void Page_Load(object sender, EventArgs e)
{
    if (Request.RawUrl.Contains("UploadImage"))
    {
        int projectID = 0, materialID = 0;
        if (Request["projectID"] != null)
            projectID = int.Parse(Request["projectID"]);
        if (Request["materialID"] != null)
            materialID = int.Parse(Request["materialID"]);
        UploadImage(Request["description"], projectID);

    }
}



    [WebMethod]
public static string UploadImage(string description, int projectID)
{
    if (HttpContext.Current.Request.Files.Count > 0 &&   HttpContext.Current.Request.Files[0] != null)
    {
        document d = new document();
        document savedDocument = d.CreateDocument(description, projectID, 0);
        JsonSerializerSettings serializationSettings = new JsonSerializerSettings();
        serializationSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        string s = JsonConvert.SerializeObject(savedDocument, serializationSettings);
return s;
    }
    else
    { return ""; }

}

UploadImage returns

"{\"documentID\":82,\"description\":\"asdf\",\"location\":\"Documents/hours_01-26-2017.csv\",\"projectID\":12,\"materialID\":null,\"material\":null,\"project\":null}"
Community
  • 1
  • 1
Max Power
  • 1
  • 3

0 Answers0