我正在尝试将包含图片和2 nsstrings
的表单数据发送到php文件,我想发送名为“document”的uiimage
。image和一个{{1} }名称为“name”,另一个nsstring
名称为“userid”。
到目前为止,这是我的代码。
nsstring
答案 0 :(得分:0)
尝试使用Afnetworking 3.0
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"your server url" parameters:@{@"parameter_1":@"string 1",@"parameter_2":@"string 2"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:@"recipeImage.jpg" mimeType:@"image/jpeg"];
}
}error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", [[NSString alloc]initWithData:[[error valueForKey:@"userInfo"] valueForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
} else {
NSLog(@"%@",responseObject);// your response here
callback(YES,responseObject);
}
}];
[uploadTask resume];
答案 1 :(得分:-1)
NSData *dataImage = UIImagePNGRepresentation(yourImage);
NSString *imageBase64 = [dataImage base64forData];
- (NSString*)base64forData
{
const uint8_t* input = (const uint8_t*)[self bytes];
NSInteger Datalength = [self length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((Datalength + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < Datalength; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < Datalength) {
value |= (0xFF & input[j]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < Datalength ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < Datalength ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}