我想通过将图片转换为base 64和UIImage
来将NSData
上传到.Net服务器。但我得到的响应为null。这是我的代码。
NSString *base64Encoded = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSString *post= [NSString stringWithFormat:@"myServerSideUrl?Image=%@",base64Encoded];
NSLog(@"PostData: %@",post);
NSString* webStringURL = [post stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:webStringURL];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSData *responseData = [[NSData alloc]initWithData:urlData];
if ([response statusCode] >=200 )
{
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: responseData options:0 error:nil];
NSLog(@"%@",jsonData);
}
过了一段时间,我刚刚检查邮递员显示的网址太长HttpResponseCode:414。此外,我尝试使用AFNetwork以NSData
格式发送图像,获得相同的响应。我只是用Google搜索了这个,就像发送基本64字符串一样。当我尝试在体内发送图像时,服务器端无法获取图像。他们正在创建像GET方法的API,但实际的方法是POST。有没有其他解决方案。有什么建议。
答案 0 :(得分:0)
您正在将NSData设置为您的请求正文,而不定义任何键值对。
使用AFNetworking尝试此代码...
- (void) uploadFileRequestWithHttpHeaders:(NSMutableDictionary*) headers
withServiceName:(NSString*) serviceName
withParameters:(NSMutableDictionary*) params
withFileData:(NSArray*) files
{
NSString *serviceUrl = [httpBaseURL stringByAppendingPathComponent:serviceName];
if (headers == nil)
{
NSDictionary *headers = [[NSDictionary alloc] initWithObjectsAndKeys:@"multipart/form-data",@"Content-Type",nil];
[self setHeaders:headers];
}
else
{
[headers setObject:@"multipart/form-data" forKey:@"Content-Type"];
[self setHeaders:headers];
}
[httpSessionManager POST:serviceUrl
parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (NSData *fileData in files)
{
[formData appendPartWithFileData:fileData name:@"userProfileImg" fileName:@"profile_pic.jpg" mimeType:@"image/jpeg"];
}
}
success:^(NSURLSessionDataTask *task, id responseObject) {
if (success != nil)
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure != nil)
}];
}
- (void) setHeaders:(NSDictionary*) headers
{
if (headers != nil)
{
NSArray *allHeaders = [headers allKeys];
for (NSString *key in allHeaders)
{
[httpSessionManager.requestSerializer setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
}
- (void) addQueryStringWithParams:(NSDictionary*) params
{
[httpSessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
__block NSMutableString *query = [NSMutableString stringWithString:@""];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
query = jsonString;
return query;
}];
}
并像这样调用这个方法..
NSArray *objects = [NSArray arrayWithObjects:@"multipart/form-data",@"1.0",@"ios",token, nil];
NSArray *Keys = [NSArray arrayWithObjects:@"content-type",@"version",@"os",@"token", nil];
NSMutableDictionary *headers = [[NSMutableDictionary alloc]initWithObjects:objects forKeys:Keys];
NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
[paraDic setObject:self.userNameField.text forKey:@"name"];
NSData * userProfileImg = UIImageJPEGRepresentation(image, 0.8f);
imageDataArray = [NSArray arrayWithObjects:userProfileImg, nil];
[self uploadFileRequestWithHttpHeaders:headers withServiceName:@"updateProfile" withParameters:params withFileData:files];
答案 1 :(得分:0)
您可以使用NSURLSession
-
- (void)postRequestForSubmitDataToServer {
//Put your action URL
NSURL *aUrl = [NSURL URLWithString:@"action_url.php?&attachment=att&submit=submit"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
//change JSON type according to ur need.
NSArray *JSON = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(@"Data = %@",JSON);
} else {
NSLog(@"%@", error);
}
}];
[postDataTask resume];
}
我的表单数据 -
<form action="action_url.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="attachment" size="25" /><br>
<input type="submit" name="submit" value="Submit" /> </form>