Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 上载图像时,对象引用未设置为Object.postmethod POST文件名文件的实例,但**可正确使用Android代码**_Ios_Asp.net_Objective C_Xcode_Nsurlconnection - Fatal编程技术网

Ios 上载图像时,对象引用未设置为Object.postmethod POST文件名文件的实例,但**可正确使用Android代码**

Ios 上载图像时,对象引用未设置为Object.postmethod POST文件名文件的实例,但**可正确使用Android代码**,ios,asp.net,objective-c,xcode,nsurlconnection,Ios,Asp.net,Objective C,Xcode,Nsurlconnection,当我向ASP.net服务器发送请求(从objective c)时,我得到的响应是对象引用未设置为Object.postmethod POST文件名文件的实例 目标c代码 NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"arrow-next"]); NSMutableURLRequest *request = [[NSMutableURLRequest alloc]

当我向ASP.net服务器发送请求(从objective c)时,我得到的响应是对象引用未设置为Object.postmethod POST文件名文件的实例

目标c代码

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代码

 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);
    }
 }
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
}
编辑:

工作的Android代码

 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);
    }
 }
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
}
HttpClient-HttpClient=newdefaulthttpclient();
mv=新的MyVars();
myUrl=mv.upload_file+pick_image_name+“&file=“+imageEncoded;
myUrl=myUrl.replaceAll(“\n”和“);
myUrl=myUrl.replaceAll(“,“%20”);
System.out.println(“完整的添加语句url为:“+myUrl”);
HttpPost HttpPost=新的HttpPost(“http://aamc.kleward.com/OfflineCourse/iphone_Upload.aspx"); // 在此处设置URL链接
试一试{
//添加数据…以单独的方式添加数据。。。
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“文件名”,选择图像名称));
添加(新的BasicNameValuePair(“文件”,imageEncoded));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
System.out.println(“====================================================”+httppost.toString());
//执行HTTP Post请求
HttpResponse response=httpClient.execute(httppost);
//System.out.println(“httpResponse”);//将此httpResponse用于JSON对象。。。。。
InputStream InputStream=response.getEntity().getContent();
InputStreamReader InputStreamReader=新的InputStreamReader(
输入流);
BufferedReader BufferedReader=新的BufferedReader(
输入流阅读器);
StringBuilder StringBuilder=新的StringBuilder();
字符串bufferedStrChunk=null;
while((bufferedStrChunk=bufferedReader.readLine())!=null){
追加(bufferedStrChunk);
}
jsonString=stringBuilder.toString();
System.out.println(“完整响应为:“+jsonString”);
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
}捕获(IOE异常){
//TODO自动生成的捕捉块
}
我无法理解响应,有人能告诉我这些响应对象引用未设置为对象实例的含义吗。postmethod POST filename file

 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);
    }
 }
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
}

以及为什么它使用Android代码?

在您的
ASP.NET
页面中,您正在从发布的表单中读取文件和文件名

在您的Android代码中,您正在将文件和文件名添加到表单,并且您的
ASP.NET
页面能够读取它,因此,没有问题

但是,在您的objective c代码中,您正在将文件和文件名添加到请求的,因此
ASP.NET
文件试图从表单读取它们时抛出异常,因为它试图读取
null
的表单变量

只需尝试将文件和文件名添加到表单中,而不是在
目标C
代码中添加标题,所有操作都会成功

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);
    } 
}];

谢谢你的回复。你能给我看些代码让我明白吗?