lantianyiming
lantianyiming
2013-07-12 03:43
采纳率: 79.6%
浏览 2.9k
已采纳

图片没有上传到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 07: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');
    
    点赞 评论

相关推荐