【问题标题】:Upload image from iPhone to server using WCF service using SOAP使用 SOAP 使用 WCF 服务将图像从 iPhone 上传到服务器
【发布时间】:2015-03-16 13:15:21
【问题描述】:

hiii,我正在为我的应用程序使用 wcf SOAP 服务,我发送如下请求。

postStr = [NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n"
           "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
           "<s:Body>\n"
           "<InsUpdDelActivityInfo xmlns=\"http://tempuri.org/\">\n"
           "<objEventsContent xmlns:d4p1=\"http://schemas.datacontract.org/2004/07/iCampuslite.Model.ActivityStream\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
           "<d4p1:ActCommentId i:nil=\"true\" />\n"
           "<d4p1:ActSubTypeCd i:nil=\"true\" />\n"
           "<d4p1:ActType>Status</d4p1:ActType>\n"
           "<d4p1:ActTypeCd>1</d4p1:ActTypeCd>\n"
           "<d4p1:ActivityAnswersList />\n"
           "<d4p1:ActivityComments />\n"
           "<d4p1:ActivityId i:nil=\"true\" />\n"
           "<d4p1:ActivityLike />\n"
           "<d4p1:ActivityName>%@</d4p1:ActivityName>\n"
           "<d4p1:ActivityStreamImagesBytes>%@</d4p1:ActivityStreamImagesBytes>\n"
           "<d4p1:AnswerDesc i:nil=\"true\" />\n"
           "<d4p1:AnswerId>0</d4p1:AnswerId>\n"
           "<d4p1:CommentDesc i:nil=\"true\" />\n"
           "<d4p1:CommentId i:nil=\"true\" />\n"
           "<d4p1:CreatedUserId>%@</d4p1:CreatedUserId>\n"
           "<d4p1:CreatedUserName i:nil=\"true\" />\n"
           "<d4p1:FileOrLinkName i:nil=\"true\" />\n"
           "<d4p1:IsLiked>0</d4p1:IsLiked>\n"
           "<d4p1:IsTotalSchool i:nil=\"true\" />\n"
           "<d4p1:LikeCount>0</d4p1:LikeCount>\n"
           "<d4p1:LinkImage i:nil=\"true\" />\n"
           "<d4p1:ObjTypeCdId i:nil=\"true\" />\n"
           "<d4p1:ObjTypeId i:nil=\"true\" />\n"
           "<d4p1:OperationMode>I</d4p1:OperationMode>\n"
           "<d4p1:OperationType i:nil=\"true\" />\n"
           "<d4p1:OperationTypeId i:nil=\"true\" />\n"
           "<d4p1:OrganizationId>%@</d4p1:OrganizationId>\n"
           "<d4p1:OtherActivityId i:nil=\"true\" />\n"
           "%@\n"
           "</objEventsContent>\n"
           "<ismobile>true</ismobile>\n"
           "</InsUpdDelActivityInfo>\n"
           "</s:Body>\n"
           "</s:Envelope>", statusText, [appDelegateObj.loginUserInfoDict valueForKey:@"a:UserId"], [appDelegateObj.loginUserInfoDict valueForKey:@"a:OrgId"], workspaceStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@iCampusliteMobileService/ActivityStreamSl.svc", appDelegateObj.baseURL]]];
NSString *messageLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postStr length]];
[request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"http://tempuri.org/IActivityStreamSl/InsUpdDelActivityInfo" forHTTPHeaderField:@"SOAPAction"];
[request addValue:messageLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

在上面的请求中有一个元素 ActivityStreamImagesBytes 是 base64binary 参数我必须传递图像。

我尝试过使用许多不同的格式。

这里是 wcf 服务截图

这是服务器端代码

public string byteArrayToImage(byte[] byteArrayIn,string fileName)
    {
        if (byteArrayIn != null)
        {
            ActivityStreamSl.LogMsg("Byte Array Count : "+byteArrayIn.Length.ToString(), "D:\\log.txt");
            var serverfile = "D:somepath\somepath\somefolder";
            var getfile = HelperClass.Filesavehelper(Constants.UploadPaths.ActivityStream, "testfilename.png", serverfile);

            FileStream file = new FileStream(getfile, FileMode.Create);
            file.Write(byteArrayIn, 0, byteArrayIn.Length);
            file.Close();
            file.Dispose();
            return getfile;
        }
        else
        {
            ActivityStreamSl.LogMsg("Byte array is null","D:\\log.txt");
        }
        return "";
    }

服务器需要一个字节数组,我不知道如何发送它? 而且我不知道什么是 base64binary 数据类型? 我是否必须从NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:@"popular.png"], 0.7);发送base64编码的字符串或字节数组或只是图像数据

任何帮助都是可观的

【问题讨论】:

  • 你见过这个问题吗? stackoverflow.com/questions/19893/… 根据它,您需要使用 Base64 对二进制数据进行编码,然后将属性 dt:dt="binary.base64 添加到节点。顺便说一句,在这种情况下,您可以使用 [NSData dataWithContentsOfFile:]

标签: ios xcode wcf soap image-uploading


【解决方案1】:

WCF 服务明确要求 base64binary,因此您必须仅以 base64binary 的形式发送。

base64binary 只不过是base64 编码的二进制数据。

1) 使用以下代码sn -p 将图像转换为二进制

NSData *binaryImageData  = UIImageJPEGRepresentation([UIImage imageNamed:@"Photo.png"], 0.0);

2) 将二进制编码为base64格式

这是我用来处理 base64 二进制和 UIImage 的类

 @interface base64BinaryandImagehandler:NSObject
   +(NSString *) base64BinaryStringFromBinaryData: (NSData *)data length: (int)length;
   +(UIImage*)Base64BinaryToImage:(NSString *)Base64;
 @end


 @implementation base64BinaryandImagehandler:NSObject
      static char base64EncodingTable[64] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
     };

 +(NSString *) base64BinaryStringFromBinaryData: (NSData *)data length: (int)length{          

 unsigned long ixtext, lentext;

    long ctremaining;

    unsigned char input[3], output[4];

    short i, charsonline = 0, ctcopy;

    const unsigned char *raw;

    NSMutableString *result;

    lentext = [data length];

    if (lentext < 1)
        return @"";

    result = [NSMutableString stringWithCapacity: lentext];

    raw = [data bytes];

    ixtext = 0;

    while (true) {

        ctremaining = lentext - ixtext;

        if (ctremaining <= 0)
            break;

        for (i = 0; i < 3; i++) {
            unsigned long ix = ixtext + i;
            if (ix < lentext)
                input[i] = raw[ix];
            else
                input[i] = 0;
        }

        output[0] = (input[0] & 0xFC) >> 2;

        output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);

        output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);

        output[3] = input[2] & 0x3F;

        ctcopy = 4;

        switch (ctremaining) {
            case 1:
                ctcopy = 2;
                break;

            case 2:
                ctcopy = 3;
                break;
        }

        for (i = 0; i < ctcopy; i++)
            [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];

        for (i = ctcopy; i < 4; i++)
            [result appendString: @"="];

        ixtext += 3;

        charsonline += 4;

        if ((length > 0) && (charsonline >= length))
            charsonline = 0;
    }
    return result;
      }

  +(UIImage*)Base64BinaryToImage:(NSString *)Base64{      


        NSString* base64String=[[NSString alloc]initWithFormat:@"data:image/png;base64,%@",Base64];

       NSURL *base64url = [NSURL URLWithString:base64String];

       NSData *imageData = [NSData dataWithContentsOfURL:base64url];

       UIImage *img=[UIImage imageWithData:imageData];

      return img;
     }
 @end 

这里是二进制转base64binary的方法

NSString *Base64Binary=[base64BinaryandImagehandler base64BinaryStringFromBinaryData:binaryImageData length:binaryImageData.length];

您还可以找到有关here 的更多信息

这里是C#中的base64编码和解码部分

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

你可以忽略 C# 部分,因为你只做 iPhone 部分。

您可以使用下面的链接来测试您的编码 base 64 是否正确。

base64toimage converter

更新 1 这是确认接收到的字符串是否为 base64 格式的代码

   private bool IsBase64String(string str){
    try{
    // If not exception is caught, then it is a base64 string
    MemoryStream stream = new MemoryStream(Convert.FromBase64String(str));
    return true;
    }
    catch{
    // If exception is caught, then I assumed it is a normal string
    return false;
    }
    }

Reference

以下代码将在 Images 文件夹下为给定的到达 base64 数据 和您选择的 文件名 创建一个图像例如duraiamuthan.jpg 并返回图像的路径,以便您可以在数据库中更新它 (它将检查到达的数据是base64还是二进制[以防WCF框架在内部将base64转换为二进制])

  public string Getpath_CreateImageFromEncodedData(string Base64EncodedData, string fileName)
        {
        string fileHandle = "";
        try
        {
            if(IsBase64String(Base64EncodedData))
            byte[] imageBytes = Convert.FromBase64String(Base64EncodedData);
            else
            byte[] imageBytes= Base64EncodedData;

            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

            ms.Write(imageBytes, 0, imageBytes.Length);

            fileHandle = System.Web.HttpContext.Current.Server.MapPath("Images/" + fileName);

            FileStream fsObj = new FileStream(fileHandle, FileMode.Create, FileAccess.Write);

            ms.WriteTo(fsObj);

            fsObj.Close();

            ms.Close();

            return fileHandle;

        }
        catch (Exception ex)
        {
           return "";
        }

    }        

更新 2(针对超时问题)

  • NSURLRequest 和 NSMutableURLRequest 默认超时时间为 60 秒数取决于互联网连接,互联网流量 网络服务器拥塞,图像创建时间和所有可能不是 足够。所以您可以使用以下方法将值设置为高于该值 语法[urlReqObj setTimeoutInterval:180]; 超时间隔为 只需几秒钟。

  • 增加 IIS 默认值是 120 秒,如果请求中的请求队列太多,有时会失败。增加 ConnectionTimeOut 会有所帮助。(此超时也是连接的空闲时间)。设置它在 IIS 高级设置中 单击您的service in IIS Manager -&gt; Advanced Settings -&gt; Connection Limits,您可以在其中设置超时,或者您可以简单地覆盖web.config 中的连接超时。

  • 打开Keep-alive in IIS 以便重复使用相同的连接,从而提高IIS 的效率。 点击你的service in IIS Manager -&gt; Advanced Settings -&gt; Connection Limits -&gt; Enable HTTP Keep-Alives

  • 如果您打算将图像的二进制存储在DB中。您可以在connectionstring中增加DB connectiontimeout或者您可以增加sqlcommandtimeout

希望这会有所帮助。 有任何疑问欢迎追问

【讨论】:

  • 嗨@Duraiamuthan.H。感谢您的答复。但是我已经尝试了上述方法,但没有任何反应。你能看到我的服务器端代码吗?可能是它的错误。你能检查一次吗?我也发过了。它需要一个字节数组。不是 base64 编码的字符串。谢谢
  • @sreekanthk - 欢迎!我已经更新了我的答案!如果您遇到任何问题,请随时询问。
  • 好的。我在做这个工作。我会让你知道结果。谢谢
  • 您好,我遇到了请求超时问题。你能帮我解决这个问题吗?
  • 这是另一个与在服务器上上传图像和大小问题有关的答案..stackoverflow.com/a/29198665/730807 在其他一些情况下会对您有所帮助
【解决方案2】:

嘿嘿, 我知道我的问题是什么

在服务器端,它需要一个字节数组,

所以,我必须按如下方式发送我的请求。

将base64字符串转换为字节数组

postStr = [NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n"
       "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
       "<s:Body>\n"
       "<InsUpdDelActivityInfo xmlns=\"http://tempuri.org/\">\n"
       "<objEventsContent xmlns:d4p1=\"http://schemas.datacontract.org/2004/07/iCampuslite.Model.ActivityStream\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
       "<d4p1:ActCommentId i:nil=\"true\" />\n"
       "<d4p1:ActSubTypeCd i:nil=\"true\" />\n"
       "<d4p1:ActType>Status</d4p1:ActType>\n"
       "<d4p1:ActTypeCd>1</d4p1:ActTypeCd>\n"
       "<d4p1:ActivityAnswersList />\n"
       "<d4p1:ActivityComments />\n"
       "<d4p1:ActivityId i:nil=\"true\" />\n"
       "<d4p1:ActivityLike />\n"
       "<d4p1:ActivityName>%@</d4p1:ActivityName>\n"
       "<d4p1:ActivityStreamImagesBytes dt: dt:"Base64Binary"><dt:length>%d</dt:length><dt:byte>%@</dt:byte>......................................</d4p1:ActivityStreamImagesBytes>\n"
       "<d4p1:AnswerDesc i:nil=\"true\" />\n"
       "<d4p1:AnswerId>0</d4p1:AnswerId>\n"
       "<d4p1:CommentDesc i:nil=\"true\" />\n"
       "<d4p1:CommentId i:nil=\"true\" />\n"
       "<d4p1:CreatedUserId>%@</d4p1:CreatedUserId>\n"
       "<d4p1:CreatedUserName i:nil=\"true\" />\n"
       "<d4p1:FileOrLinkName i:nil=\"true\" />\n"
       "<d4p1:IsLiked>0</d4p1:IsLiked>\n"
       "<d4p1:IsTotalSchool i:nil=\"true\" />\n"
       "<d4p1:LikeCount>0</d4p1:LikeCount>\n"
       "<d4p1:LinkImage i:nil=\"true\" />\n"
       "<d4p1:ObjTypeCdId i:nil=\"true\" />\n"
       "<d4p1:ObjTypeId i:nil=\"true\" />\n"
       "<d4p1:OperationMode>I</d4p1:OperationMode>\n"
       "<d4p1:OperationType i:nil=\"true\" />\n"
       "<d4p1:OperationTypeId i:nil=\"true\" />\n"
       "<d4p1:OrganizationId>%@</d4p1:OrganizationId>\n"
       "<d4p1:OtherActivityId i:nil=\"true\" />\n"
       "%@\n"
       "</objEventsContent>\n"
       "<ismobile>true</ismobile>\n"
       "</InsUpdDelActivityInfo>\n"
       "</s:Body>\n"
       "</s:Envelope>", statusText, [byteArray length], byteArray[0], byteArray[1], .................................., [appDelegateObj.loginUserInfoDict valueForKey:@"a:UserId"], [appDelegateObj.loginUserInfoDict valueForKey:@"a:OrgId"], workspaceStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@blah....blah....blah....", appDelegateObj.baseURL]]]; NSString *messageLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postStr length]]; [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request addValue:@"http://tempuri.org/blah......blah.....blah............" forHTTPHeaderField:@"SOAPAction"]; [request addValue:messageLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[postStr dataUsingEncoding:NSUTF8StringEncoding]]; NSError *error = nil; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&amp;error];

我已经托管了这些服务,并且在那里我看到了请求的 xml 格式。无论如何谢谢@Duraiamuthan.H

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多