简体   繁体   English

将图像从iOS应用程序上传到php-不太正确-我缺少什么?

[英]Upload image from iOS app to php — Can't quite get it right — What am I missing?

Firstly, I know this question has been asked a thousand times. 首先,我知道这个问题已经问了一千遍了。 I'm asking again because I've tried the solutions in the other examples and they are not working for me and I don't know why. 我再次询问是因为我在其他示例中尝试了解决方案,但它们对我不起作用,我也不知道为什么。 Everyone seems to have a slightly different approach. 每个人似乎都有不同的方法。

NSData *imageData =  UIImagePNGRepresentation(form.image);
NSURL *url = [NSURL URLWithString:@"myscript.php"];
NSMutableString *postParams = [[NSMutableString alloc] initWithFormat:@"&image=%@", imageData]];

NSData *postData = [postParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [[NSString alloc] initWithFormat:@"%d", [postData length]];

NSMutableURLRequest *connectRequest = [[NSMutableURLRequest alloc] init];
[connectRequest setURL:url];
[connectRequest setHTTPMethod:@"POST"];
[connectRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[connectRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//[connectRequest setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
[connectRequest setHTTPBody:postData];

NSData *receivedData;
NSDictionary *jsonData;

NSURLConnection *connectConnection = [[NSURLConnection alloc] initWithRequest:connectRequest delegate:self];

NSError *error = nil;

if (!connectConnection) {
    receivedData = nil;
    NSLog(@"The connection failed!");
} else {
    NSLog(@"Connected!");
    receivedData = [NSURLConnection sendSynchronousRequest:connectRequest returningResponse:NULL error:&error];
}

if (!receivedData) {
    NSLog(@"Data fetch failed: %@", [error localizedDescription]);
} else {
    NSLog(@"The data is %lu bytes", (unsigned long)[receivedData length]);
    NSLog(@"%@", receivedData);

    if (NSClassFromString(@"NSJSONSerialization")) {
        id object = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];

        if (!object) {
            NSLog(@"JSON Serialization failed: %@", [error localizedDescription]);
        }

        if ([object isKindOfClass:[NSDictionary class]]) {
            jsonData = object;
            NSLog(@"json data: %@", jsonData);
        }
    }
}

At the moment I am passing the NSData in the postParams and using this php script: 目前,我在postParams中传递NSData并使用以下php脚本:

if (isset($_POST['image']) && !empty($_POST['image'])) {

     if (file_put_contents('images/test.png', $_POST['image'])) {
           echo '{"saved":"YES"}'; die();
     } else {
           echo '{"saved":"NO"}'; die();     
     }
}

This is saving the data to a file but I can't open it as it is corrupted or some such thing. 这是将数据保存到文件中,但由于损坏或某些类似的事情,我无法打开它。 This was pretty much a last ditch effort and I didn't really expect it to work this way but it's as close as I've come so far to getting it right. 这几乎是最后的努力,我并没有真正期望它能以这种方式工作,但它与我迄今为止为实现正确目标所做的努力差不多。

I've tried using various content header/ boundary / $_FILES / enctype content-type methods but I can't even get it to send to the script properly like that. 我尝试使用各种内容标头/边界/ $ _ FILES / enctype内容类型方法,但我什至无法像这样正确地将其发送到脚本。

  • incidentally, I'm not just sending the image data, I'm also posting other values in the postParams that are just strings, ints, etc. 顺便说一句,我不仅在发送图像数据,而且还在postParams中发布了其他值,这些值仅仅是字符串,整数等。

Does anyone have any suggestions or know of any good sources out there for this? 有没有人对此有任何建议或任何好的消息来源?

Thanks for any assistance offered. 感谢您提供的任何帮助。


Current state after following advice given in answers below (also, further information from other parts of program): 遵循以下答案中给出的建议后的当前状态(以及程序其他部分的更多信息):

Initial capture of image: 图像的初始捕获:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [self.view endEditing:YES];

    __unused form *form = self.form;

    form.signature = self.signatureDrawView.bp;

    UIGraphicsBeginImageContext(self.signatureDrawView.bounds.size);
    [self.signatureDrawView.layer renderInContext:UIGraphicsGetCurrentContext()];
    campaignForm.signatureImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

where the signatureDrawView is a UIView and the form.signature is a UIBezierpath. 其中signatureDrawView是一个UIView,而form.signature是一个UIBezierpath。


then... 然后...

NSData *sigImage =  UIImagePNGRepresentation(campaignForm.signatureImage);

which is passed to the following function: 传递给以下函数:

- (void)uploadImage:(NSData *)imageData
{
    NSMutableURLRequest *request;
    NSString *urlString = @"https://.../upload.php";
    NSString *filename = @"uploadTest";
    request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@.png\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:imageData]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString;
    returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", returnString);
}

upload.php looking like: upload.php看起来像:

    if ($_FILES["file"]["error"] > 0) {
        echo '{"file":"'.$_FILES['file']['error'].'"}';
        die();
    } else {
        $size = $_FILES["file"]["size"] / 1024;
        $upload_array = array(
                    "Upload"=>$_FILES["file"]["name"],
                    "Type"=>$_FILES["file"]["type"],
                    "Size"=>$size,
                    "Stored in"=>$_FILES["file"]["tmp_name"]
                    );
        //echo json_encode($upload_array);
        if (move_uploaded_file($_FILES["file"]["tmp_name"], "signatures/" . $_FILES["file"]["name"])) {
            echo '{"success":"YES"}';
            die();  
        } else { 
            echo '{"success":"NO"}';
            die();  
        }
        die();
    }

This is giving me the {success:NO} output and the $upload_array dump shows null values. 这给了我{success:NO}输出,并且$ upload_array转储显示空值。

Put following code, may you get help 输入以下代码,可能会得到帮助

NSData *myData=UIImagePNGRepresentation([self.img image]);
NSMutableURLRequest *request;
NSString *urlString = @"http://xyzabc.com/iphone/upload.php";
NSString *filename = @"filename";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:myData]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString;
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM