IOS — Загрузить форму с изображением и nsstrings в файл PHP

Я пытаюсь отправить данные формы, которая имеет изображение и 2 nsstrings в файл php, и я хочу отправить uiimage.Изображение с названием «документ» и один nsstring с именем «имя» и другим nsstring с именем «userid».

Вот мой код до сих пор.

    NSData *imageData = UIImageJPEGRepresentation(Myimage.image, 1.0);
if (imageData != nil)
{
NSString *filename = [NSString stringWithFormat:@"%@",name];      //set name here
NSLog(@"%@", filename);
NSString *urlString = @"http://URL/upload.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filenames\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[filename dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);
NSLog(@"finish");
}

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];
0

Другие решения

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];}
-1

По вопросам рекламы [email protected]