0

在此处使用 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 文件,未编辑)对其进行了测试,并且文件以全尺寸上传。

我知道这种上传文件的方法很危险,但目前这是我唯一得到的。

任何想法为什么我的文件没有被上传?谢谢。

4

1 回答 1

0

好的,我听从了您的建议并实际使用了 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];
于 2013-06-21T21:57:30.887 回答