我正在尝试使用 http-post 请求从我保存的照片(iPhone 4)上传图像。我得到了 uploader.php,它可以很好地将 $_FILES 移动到正确的位置。但最后,当图片上传时,我看到了这个:
我花了几个小时试图解决这个问题并在这里寻找相关的问题,但对我没有任何帮助。
-(void)sendImage:(UIImage*)image{
NSString *url = @"http://www.mypage.vv.si/uploader.php";
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0f];
[theRequest setHTTPMethod:@"POST"];
NSString *boundary = @"UVYDTNFMLFUVTTCECELPLCPELCPE";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[theRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
if (imageData)
{
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"Content-Length %d\r\n\r\n", [imageData length] ] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *timeStr = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
timeStr = [timeStr stringByReplacingOccurrencesOfString:@"." withString:@""];
NSString *uniqueFileName = [NSString stringWithFormat:@"img%@.jpg", timeStr];
NSString *contDispos = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", uniqueFileName];
[body appendData:[contDispos dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPBody:body];
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
if (connection) {
self.infoData = [NSMutableData data];
} else {
NSLog(@"Connection failed");
}
}
else
NSLog(@"No Data!");
}