我正在尝试将jpg图像上传到我的服务器几个小时。我发现了很多关于该主题的问题和解决方案,但我没有得到它。 这是我到目前为止所得到的:
XCODE:
- (void) upload {
UIImage *img = [UIImage imageNamed:@"test.jpg"];
NSData *imageData = UIImageJPEGRepresentation(img ,90);
long imageSize = (long)[imageData length];
NSLog(@"SIZE OF IMAGE: %.2f Mb", (float)imageSize/1024/1024);
NSString *urlString = @"http://www.MYURL.com/upload.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:urlString]] ;
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"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=\"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(@"%@data",returnString);
}
PHP:
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['picture']['name']);
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name'])." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
我将完整权限设置为服务器上的目录,因此不应该是错误。
这个问题的一些帮助会让我真的很幸运!