在这里使用ASIFormDataRequest搜索一个简单的图像上传之后,我终于让它正常工作了(有点),但是出现了一个意外的错误。
我的图像被上传到我的服务器上,但它是空白,大小为0字节。这是我的代码:
-(IBAction)uploadImage:(id)sender
{
NSData *data = UIImageJPEGRepresentation(self.imageView.image,0.6f);
NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:@"upload.png"];
[data writeToFile:file atomically:YES];
NSString *strURL = @"http://domain.com/upload.php";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
UIImage *image1=[UIImage imageNamed:file];
NSData *imageData1=UIImageJPEGRepresentation(image1, 1.0);
[request setData:imageData1 withFileName:file andContentType:@"image/jpeg" forKey:@"avatar"];
[request setRequestMethod:@"POST"];
//[request appendPostData:body];
[request setDelegate:self];
[request setTimeOutSeconds:13.0];
request.shouldAttemptPersistentConnection = NO;
[request setDidFinishSelector:@selector(uploadRequestFinished:)];
[request setDidFailSelector:@selector(uploadRequestFailed:)];
[request startAsynchronous];
}
- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
NSLog(@" Error - Statistics file upload ok: \"%@\"",[request responseString]);
}
- (void)uploadRequestFailed:(ASIHTTPRequest *)request{
NSLog(@" Error - Statistics file upload failed: \"%@\"",[[request error] localizedDescription]);
}我的PHP代码:
<?php
$target = "./";
$target = $target . basename( $_FILES['avatar']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['avatar']['tmp_name'], $target))
{
echo "The file ok";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>起初,我认为这是一个文件夹过滤的事情,但我用一个简单的html表单上传(使用相同的php文件,未经编辑)来测试它,该文件是完全上传的。
我知道这种上传文件的方法是危险的,但就目前而言,这是我唯一能得到的东西。
知道为什么我的文件没被上传吗?谢谢。
发布于 2013-06-21 21:57:30
好的,我遵循了您的建议,实际上使用了AFNetwork,这是我帮助他人的代码。
NSData *imageToUpload = UIImageJPEGRepresentation(_imageView.image, 0.5f);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://domain.com"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:@"avatar" fileName:fullFilename mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(@"response: [%@]",response);
[MBProgressHUD hideHUDForView:self.view animated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(@"Upload Failed");
return;
}
NSLog(@"error: %@", [operation error]);
}];
[operation start];https://stackoverflow.com/questions/17242680
复制相似问题