Object reference not set to an instance of an object.postmethod POST filename file while uploading image but **works correctly with Android code**

StackOverflow https://stackoverflow.com/questions/22283595

Question

I am getting Object reference not set to an instance of an object.postmethod POST filename file in response when I send a request (from objective c) to ASP.net server.

objective c code

NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"arrow-next"]);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                initWithURL:[NSURL URLWithString:@"http://aamc.kleward.com/OfflineCourse/iphone_Upload.aspx"]
                                cachePolicy:NSURLCacheStorageNotAllowed
                                timeoutInterval:120.0f];

[request addValue:@"text/plain; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];

[request addValue:[data base64Encoding] forHTTPHeaderField:@"file"];
[request addValue:@"myimage.png" forHTTPHeaderField:@"filename"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    if (!connectionError) {
        NSLog(@"response--%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
    else{
        NSLog(@"error--%@",connectionError);
    }
}];

ASP.net code

 private string UploadFile(byte[] file, string fileName)
{
    // the byte array argument contains the content of the file
    // the string argument contains the name and extension
    // of the file passed in the byte array
    string sJSON = "{\"Root\":[";
    try
    {
        // instance a memory stream and pass the
        // byte array to its constructor
        MemoryStream ms = new MemoryStream(file);
        // instance a filestream pointing to the
        // storage folder, use the original file name
        // to name the resulting file

        FileStream fs = new FileStream(//System.Web.Hosting.HostingEnvironment.MapPath
                    System.Configuration.ConfigurationManager.AppSettings["PDPointFile"].ToString() + fileName, FileMode.Create);

        // write the memory stream containing the original
        // file as a byte array to the filestream
        ms.WriteTo(fs);

        // clean up
        ms.Close();
        fs.Close();
        fs.Dispose();
        // return OK if we made it this far
        sJSON += "{\"Value\":\"True\",";
        sJSON += "\"File Path\":\"" + System.Configuration.ConfigurationManager.AppSettings["PDPointFilePath"].ToString() + fileName + "\"}]}";
        Response.Write(sJSON);
        return sJSON;
    }
    catch (Exception ex)
    {
        sJSON += "{\"Value\":\"False\",";
        sJSON += "\"File Path\":\"\"}]}";
        Response.Write(ex.Message);
        Response.Write(sJSON);
        return sJSON;
        // return the error message if the operation fails
        // return ex.Message.ToString();
    }
}

// getting value.

protected void Page_Load(object sender, EventArgs e)
 {
    try
    {
        postmethod = Request.HttpMethod;
        if (Request.HttpMethod == "POST")
        {
            str_filename = Request.Form["filename"].ToString();
            tokenID =  Server.UrlDecode(Request.Form["file"].ToString().Replace(" ", "+"));

           tokenID = tokenID.Replace(" ", "+");
           str_file = Convert.FromBase64String(tokenID);
           UploadFile(str_file, str_filename);
        }
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message + "postmethod " + postmethod + " filename " + str_filename + " file " + tokenID);
    }
 }

Edit:

working Android Code

HttpClient httpClient = new DefaultHttpClient();

mv = new MyVars();
myUrl = mv.upload_file + pick_image_name + "&file=" + imageEncoded ;
myUrl = myUrl.replaceAll("\n", "");
myUrl = myUrl.replaceAll(" ", "%20");
System.out.println("Complete Add statement url is : " + myUrl);
HttpPost httppost = new HttpPost("http://aamc.kleward.com/OfflineCourse/iphone_Upload.aspx"); // Setting URL link over here

try {
   // Add your data ... Adding data as a separate way ...
   List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
   nameValuePairs.add(new BasicNameValuePair("filename", pick_image_name));
   nameValuePairs.add(new BasicNameValuePair("file", imageEncoded));
   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


   System.out.println("================== URL HTTP ===============" + httppost.toString());

   // Execute HTTP Post Request
   HttpResponse response = httpClient.execute(httppost);

  // System.out.println("httpResponse"); // use this httpresponse for JSON Object.....
  InputStream inputStream = response.getEntity().getContent();
  InputStreamReader inputStreamReader = new InputStreamReader(
  inputStream);
  BufferedReader bufferedReader = new BufferedReader(
  inputStreamReader);
  StringBuilder stringBuilder = new StringBuilder();
  String bufferedStrChunk = null;
 while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
  stringBuilder.append(bufferedStrChunk);
 }
 jsonString = stringBuilder.toString();
 System.out.println("Complete response is : " + jsonString);

 } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
} catch (IOException e) {
   // TODO Auto-generated catch block
}

I am not able to understand the response, can anyone tell me what's the meaning of these response Object reference not set to an instance of an object.postmethod POST filename file

and why it's working with Android code?

Was it helpful?

Solution

In your ASP.NET page, you're reading the file and filename from the form that was posted.

In your Android code, you're adding the file and filename to the form and your ASP.NET page is able to read it, so, no issues.

But, in your objective c code, you're adding the file and filename to the header of your request, so the ASP.NET file, trying to read them from the form throws the exception, since it's trying to read the form variables that are null.

Just try adding the file and filename to the form instead of the header in your Objective C code and all will work out.

NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"arrow-next"]);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                            initWithURL:[NSURL URLWithString:@"http://aamc.kleward.com/OfflineCourse/iphone_Upload.aspx"]
                            cachePolicy:NSURLCacheStorageNotAllowed
                            timeoutInterval:120.0f];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
NSString *postString = [NSString stringWithFormat:@"filename=%@&file=%@",@"myimage.png",[data base64Encoding]] ;
data = [postString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[data length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (!connectionError) {
        NSLog(@"response--%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    } else{
        NSLog(@"error--%@",connectionError);
    } 
}];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top