在此处使用 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 文件,未编辑)对其进行了测试,并且文件以全尺寸上传。
我知道这种上传文件的方法很危险,但目前这是我唯一得到的。
任何想法为什么我的文件没有被上传?谢谢。