繁体   English   中英

将图像从ios上传到Web服务会显示“ Base-64 char数组的长度无效”

[英]Uploading image from ios to web service gives 'Invalid length for a Base-64 char array'

我正在尝试将图像从ios应用上传到Web API服务。

我正在使用[data base64EncodedStringWithOptions]对图像进行编码,然后将其与其他一些数据组合成一个对象,然后使用NSJSONSerialization,然后将其作为“ PUT”放置在NSMutableURLRequest的主体中,然后使用NSURLSession将其发送给asp .net Web API服务。

数据到达Web服务,并使用JavaScriptSerializer反序列化。 然后,我使用Convert.FromBase64String重新创建图像。 但是,Convert.FromBase64String引发异常“ Base-64 char数组的无效长度” 图像的大小为38988字节。

为了验证这一点,我没有发送图像,而是发送包含'a','b','c','','=','f'(以及其他各种组合字符)的数组。 这完美地工作,Convert.FromBase64String不会引发任何异常。

导致此问题的图像数据可能是什么?

简化的Xcode

  NSString* const Folder = @"SomeFolder";

  NSString *fileName = [self getFileName];
  NSData *data = UIImageJPEGRepresentation(image, 0.0);
  // static char initArray[6] = {'a','b','\0',' ','e','f'};  // if i use this then it works
  // NSData* data = [[NSData alloc] initWithBytes:initArray length:6];
  NSString* sData = [data base64EncodedStringWithOptions:0];

  // set up session
  NSError *error;
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
  NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"<service url>/api/Documents/PutDoc/%@", id]];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

  NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:Folder, @"folder", fileName, @"fileName", sData, @"sImage", nil];
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];

  NSMutableData *postData = (NSMutableData*)[@"=" dataUsingEncoding:NSUTF8StringEncoding];
  [postData appendData:jsonData];
  [request setHTTPBody:postData];
  [request setHTTPMethod:@"PUT"];
  [request addValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
  [request addValue:@"*/*" forHTTPHeaderField:@"Accept"];

  // send request
  NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
      NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
      if ([httpResponse statusCode] == 200) {
        NSString* msg = [NSString stringWithFormat: @"Document Saved to server"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Document Saved" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
      } else {
        NSDictionary* dic = [httpResponse allHeaderFields];
        NSString* msg = [NSString stringWithFormat: @"Server Error. Code: %d", [httpResponse statusCode]];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Document Not Saved" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
      }
    });
  }];

Web API C#代码(简体)

  JavaScriptSerializer js = new JavaScriptSerializer();
  Document doc = (Document)js.Deserialize<Document>(value);
  byte[] img;
  try {
    img = Convert.FromBase64String(doc.sImage);
  } catch (Exception e) {
    // this is where the 'invalid length' exception is throw
    MyLib.LogIt(string.Format("Error converting: {0}", e.Message));
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) {
      Content = new StringContent("Could not convert image to binary"),
      ReasonPhrase = "Conversion Error"
    });
  }
    ..

我正在使用下面的代码将选定的图像发送到服务器,对我来说很好。

-(void)ImageUpdatewithImageID
{
imageData = UIImagePNGRepresentation(selectedImage);
NSString *strParameter = [NSString stringWithFormat:@"%@",[self.rmsDbController.globalDict objectForKey:@"BranchID"]];
NSString *strPar = [NSString stringWithFormat:@"http://www.example.com"];
NSURL *url = [NSURL URLWithString:[strPar stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request appendPostData:imageData];
[request setDidFinishSelector:@selector(uploadFinished:)];
[request setDidFailSelector:@selector(uploadFailed:)];
 [request setDelegate:self];
[request startAsynchronous];
}

- (void)uploadFinished:(ASIHTTPRequest *)request
{
        // after image successfully uploaded
}
- (void)uploadFailed:(ASIHTTPRequest *)request
{
        // if image not uploaded
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM