我的问题描述实际上是问题标题。我是网络技术的新手,所以这种行为对我来说有点引人注目。尽管图像上传已成功完成,为什么会调用失败块?此外,我搜索了关于SoF的问题的答案,并应用了一些解决方案,但这个错误仍然出现了。请尽可能帮助。提前谢谢。
目标 - C:
- (void)upload {
NSString *fileName = [NSString stringWithFormat:@"%ld%c%c.jpg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
NSData *data = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:imagePath]);
NSString *URLString = @"http://myServer/myAppFolder";
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager manager] initWithBaseURL:[NSURL URLWithString:URLString]];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager setResponseSerializer:responseSerializer];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
AFHTTPRequestOperation *operation = [manager POST:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data name:@"uploadedfile" fileName:fileName mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure / %@, / %@", error, operation.responseString); //error comes from here
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"uploading...");
}];
}
upload.php的:
<?php
$filename="uploaded";
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded";
} else {
echo "There was an error uploading the file, please try again!";
}
?>;
我收到了这个错误:
Failure / Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x8a633e0 {NSDebugDescription=Invalid value around character 0.}, / The file 1389046572lb.jpg has been uploaded;
答案 0 :(得分:1)
问题在于您使用AFJSONResponseSerializer
来序列化PHP上传脚本的响应。
并且您的PHP没有返回JSON - 因此序列化程序会抛出错误。
您可以修改PHP脚本,使其返回JSON格式的结果。或者您可以使用不同类型的序列化器。
根据this forum解决方案将使用[AFResponseSerializer serializer]
- 我不确定它是否存在。试试基本的AFHTTPResponseSerializer
。