图片上传到PHP服务器(Uploading Image to PHP Server)

2019-10-18 20:03发布

-(IBAction)TakePhoto{
    picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
    [self presentViewController:picker animated:YES completion:NULL];
    [picker release];

}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [imageView setImage:image];
    [self dismissViewControllerAnimated:YES completion:NULL];

}
-(IBAction)uploadImage{
    NSData *imageData = UIImageJPEGRepresentation(image, 90);
    NSString *urlString = @"http://myserverdomain.com/upload.php";

    NSMutableURLRequest *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 *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

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

}

在这里,我想的图像上传到我的服务器,但图像没有显示在“图片”文件夹中了。 还我收到一个警告说“未使用的变量returnString”

这里是我的PHP脚本

<?php
$msg = " ".var_dump($_FILES)." ";
$new_image_name = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], getcwd() . "/pictures/" . $new_image_name);

?>

Answer 1:

试试下面的代码:

<?php
$msg = " ".var_dump($_FILES)." ";
$new_image_name = $_FILES["userfile"]["name"];
move_uploaded_file($_FILES["userfile"]["tmp_name"], getcwd() . "/pictures/" . $new_image_name);

?>

[主体appendData:[@ “内容处置:形状数据;名称= \” userfile的\ “;文件名= \” ipodfile.jpg \ “\ r \ n” 个dataUsingEncoding:NSUTF8StringEncoding]]; 正如你所使用的文件的名称为“userfile的”,并以“文件”的名字,这就是为什么你的文件不在服务器上上传访问它的PHP文件。



文章来源: Uploading Image to PHP Server