以下代码用于将图像上传到远程服务器,但由于某种原因,它对我不起作用。 当我进入,例如到这个页面,我使用PHP表格上传图像,它没有问题。 所以,关于PHP部分,没有任何一个问题,一切正常。
这有什么问题?
NSData *imageData = UIImageJPEGRepresentation(self.imageViewer.image, 90); NSString *urlString = @"http://example.com/post_image.php"; [request setHTTPMethod:@"POST"]; 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:[@"Content-Disposition: form-data; name=\"image\"; 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]; returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *picture = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"uploaded picture: %@", picture);
答案 0 :(得分:1)
更改mime类型以匹配您实际发送的内容(image/jpeg
)。
删除其中一个重复的行:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
(可能至少记录错误参数......)