从ios上传图像到web服务给出了'Base-64字符数组的无效长度'
本文关键字:Base-64 字符 无效 数组 图像 ios web 服务 | 更新日期: 2023-09-27 18:16:25
我正在尝试从ios应用程序上传图像到web api服务。
我使用[data base64EncodedStringWithOptions]编码图像,然后组合成一个对象与其他一些数据,然后使用NSJSONSerialization,然后将其放在NSMutableURLRequest的主体作为'PUT',然后使用NSURLSession将其发送到asp.net web api服务。
数据到达web服务并使用JavaScriptSerializer进行反序列化。然后使用Convert。FromBase64String重新创建图像。然而,转换。FromBase64String抛出一个异常' Base-64字符数组的长度无效'。图片大小为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
}