2 lantianyiming lantianyiming 于 2013.07.12 11:43 提问

图片没有上传到web服务器中

上传一个图片到web服务器上,但是上传后之后图片的名字被保存了,图片没保存

代码:

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissModalViewControllerAnimated:YES];    
    NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);    
    NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"];
    [urlString appendFormat:@"%@", image];
    NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
                               allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSString *baseurl = @"http://192.168.2.34/Service1.svc/upload/filename.png";    
    NSURL *url = [NSURL URLWithString:baseurl];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"application/x-www-form-urlencoded"
      forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPBody:postData];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    [connection start];
    NSLog(@"Started!");
}

上传之后图片:

CSDN移动问答

但是打开图片时会显示空:

CSDN移动问答

1个回答

loFataMer
loFataMer   2013.07.12 15:37
已采纳

这块的代码不对:

NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"];
[urlString appendFormat:@"%@", image];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
...
[urlRequest setValue:@"application/x-www-form-urlencoded"
  forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];

应该换成:

NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);
...
[urlRequest setHTTPBody:image];

然后要将 0.1 改为 0.8 或者其他的。不然质量会失真。
需要保证服务器正确读取数据,根据你的服务器端,在PHP中:

$data = file_get_contents('php://input');
file_put_contents($data, 'filename.jpg');
Csdn user default icon
上传中...
上传图片
插入图片