上传图片到网络服务导致图片损坏。

3

我正在尝试从iPhone上传图片到Web服务,但即使文件已成功上传,JPG也无法查看,似乎已损坏。

使用以下C#代码可以成功上传文件并正常工作:

var url = http://myurl.co.uk/services/service.svc/UploadImage?id=108&ext=png;

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "image/jpeg";

using (var reqStream = req.GetRequestStream())
{
    var bytes = File.ReadAllBytes("C:\\Users\\Chris\\Pictures\\default.png”);
    reqStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);

以下是我在iOS上尝试的代码,但它无法查看文件:

获取图片

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    // Resize the image from the camera
    UIImage *scaledImage = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:CGSizeMake(_photo.frame.size.width/2, _photo.frame.size.height/2) interpolationQuality:kCGInterpolationHigh];
    // Crop the image to a square (yikes, fancy!)
    UIImage *croppedImage = [scaledImage croppedImage:CGRectMake((scaledImage.size.width -_photo.frame.size.width)/2, (scaledImage.size.height -_photo.frame.size.height)/2, _photo.frame.size.width, _photo.frame.size.height)];
    // Show the photo on the screen
    _photo.image = croppedImage;

    NSData *imgData=UIImageJPEGRepresentation(croppedImage,1);
    NSLog(@"Original size:%d",[imgData length]);
    NSData *smallerImage=UIImageJPEGRepresentation(croppedImage, 0.5);
    NSLog(@"End size:%d",[smallerImage length]);
    imageData = imgData;

    NSString *imageName = @"tempImage.jpg";
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString * documentsDirectoryPath = [paths objectAtIndex:0];

    NSString *dataPath = [documentsDirectoryPath  stringByAppendingPathComponent:imageName];
    NSData* settingsData = UIImageJPEGRepresentation(croppedImage, 0.5);

    [settingsData writeToFile:dataPath atomically:YES];

    [picker dismissModalViewControllerAnimated:YES];
}

上传图片:

-(void)uploadImageForOfferID:(NSString *)offerID imageExtention:(NSString *)extension withCompletionBlock:(void(^)(NSError *error))block
{
    NSString *imageName = @"tempImage.jpg";
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString * documentsDirectoryPath = [paths objectAtIndex:0];

    NSString *dataPath = [documentsDirectoryPath  stringByAppendingPathComponent:imageName];
    NSData* imageData = [NSData dataWithContentsOfFile:dataPath];

    AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:masterURL]];

    NSString *url = [NSString stringWithFormat:@"UploadImage?id=%@&ext=%@", offerID, extension];
    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    }];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Complete");
        block(nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failed");
        NSLog(@"FAILED WITH STATUS CODE %d - error description: %@", operation.response.statusCode, error.description);
        block(error);
    }];
    [operation start];
}

此方法先将图像保存到文件中,然后再上传。 我还尝试仅上传来自NSData *smallerImage = UIImageJPEGRepresentation(croppedImage, 0.5); 的数据,但结果相同。
上传时是否有遗漏?
谢谢
编辑 ----
比较模拟器文件和上传的文件。 模拟器文件为2,538字节(磁盘上的4 KB),上传的文件略大于2,698字节(磁盘上的4 KB)。原始模拟器图像显示缩略图,但上传的图像没有!上传的图像可以在Photoshop中打开,但不能在Safari或Chrome中打开。

将iDevice上保存的图像(使用模拟器更容易)与服务器上的图像进行比较,如果Web服务器接受了它但数据已损坏,则这是不寻常的。如果没有区别,只需等待一段时间并在不同的浏览器中打开图像即可。我之前在Mac上使用Chrome时遇到过类似的问题。图像看起来损坏了,由于某些缓存原因没有刷新,但在Firefox中看起来很好。 - demosten
请参见问题底部的编辑。比较的文件略有不同。 - Darren
这可能与主题无关,但是你的C#代码正在将PNG文件保存为JPEG格式。服务是否期望这种变化?var bytes = File.ReadAllBytes("C:\\Users\\Chris\\Pictures\\default.png”); 看起来你在iOS中的临时图像是JPG格式。 - propstm
我也注意到了。C# 代码由 Web 服务的编写者提供,以展示其工作原理。该 Web 服务设置为接受 PNG 和 JPG,使用 &ext=png 或 &ext=jpg URL 字段。 - Darren
模拟器图像的原始大小为4223,但AFNetworking发送的字节数为“已发送4382个字节中的4382个字节”。 - Darren
1个回答

0

这可能与您发送类型为image/jpeg的图像有关,而您在提供的代码中所指向的文件实际上是一个.png文件,应该使用image/png吗?


不,我已经尝试过使用image/jpegimage/png发送png和jpg文件,但AFNetworking似乎总是上传比图像本身稍微多一些的数据。 - Darren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接