0

我正在尝试运行 HTTP 请求以保存图像。PHP脚本处理POST,它似乎接收到手动设置的文件名,但文件没有大小也没有保存。

我正在使用的 Obj-C 代码是:

    MyImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSData *imageData = UIImageJPEGRepresentation(MyImage.image, 90);
    NSString *urlString = @"http://localhost/api/phptest.php";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = [NSString stringWithString:@"---------------------------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:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"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(returnString);

我的 PHP 文件看起来像:

//echo basename($_FILES['userfile']['name']);
$uploaddir = '/api/uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;

echo $uploadfile."\n";
echo $file."\n";
echo $uploaddir."\n";
echo $_FILES["file"]["type"]."\n";
echo $_FILES["file"]["size"] / 1024;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "Uploaded";
}

但是我在 XCode 中得到的回报是

2013-02-10 13:23:09.116 Dablia[3419:907] /api/uploads/ipodfile.jpg
ipodfile.jpg
/api/uploads/

0
4

1 回答 1

0

尝试更改内容类型,现在您正在使用它:

[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

试试这个:

[body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);

来自文档:

压缩质量

生成的 JPEG 图像的质量,表示为 0.0 到 1.0 之间的值。值 0.0 表示最大压缩(或最低质量),而值 1.0 表示最小压缩(或最佳质量)。

我也注意到了这一点:

[body appendData:[NSData dataWithData:imageData]];

你为什么做这个?你已经有一个 NSData 对象(imageData)

于 2013-02-10T14:00:56.887 回答