为什么上传的图片无法正常显示?

时间:2012-05-22 02:05:12

标签: php objective-c ios

我上传了一个图片文件到php服务器,该文件可以在服务器端接收但无法在Preview中显示,而服务器日志无法获取图片文件类型,应用程序代码片段如下:

@interface ImageUploader : NSObject <NSURLConnectionDataDelegate>
{
......
}

- (id)initWithURL:(NSURL*)theServerURL image:(UIImage*)theImage delegate:(id<ImageUploaderDelegate>)theDelegate;
- (void)startUpload;

@end

@implementation ImageUploader
......

- (void)startUpload
{
    NSURLRequest *request = [self postRequestWithURL:serverURL boundry:BOUNDRY image:image];
    connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
}

#pragma mark - Private Methods
- (NSURLRequest*)postRequestWithURL:(NSURL*)url boundry:(NSString*)theBoundry image:(UIImage*)theImage
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [request setHTTPShouldHandleCookies:NO];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", theBoundry] forHTTPHeaderField:@"Content-Type"];
    NSMutableData *postData = [NSMutableData data];
    NSData *imageData = UIImagePNGRepresentation(theImage);
    if (imageData) {
        [postData appendData:[[NSString stringWithFormat:@"--%@\r\n", theBoundry]dataUsingEncoding:NSUTF8StringEncoding]];
        [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"imageFileFromIPhoneApp.png\"\r\n\r\n", FORM_FLE_INPUT]dataUsingEncoding:NSUTF8StringEncoding]];
        [postData appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [postData appendData:imageData];
    }
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", theBoundry]dataUsingEncoding:NSUTF8StringEncoding]];
    [request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"]; 
    [request setHTTPBody:postData];
    return request;
}

@implementation WonderfulMomentViewController
......
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissModalViewControllerAnimated:YES];
    // do something with selectedImage and originalImage
    NSString *queryURL = [NSString stringWithFormat:@"%@/modules/party.php?action=uploadWonderfulImage", HOST_DOMAIN];
    ImageUploader *imageUploader = [[ImageUploader alloc]initWithURL:[NSURL URLWithString:queryURL] image:selectedImage delegate:self];
    [imageUploader startUpload];
}
......
@end

===============================================
the php code below:

public function uploadWonderfulImage(){
    foreach($_FILES as $key => $value){
        error_log("$key=>$value");
        foreach($_FILES[$key] as $subkey => $subvalue){
            error_log("$subkey=>$subvalue");
        }
    }
    move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $_FILES["uploadFile"]["name"]);
}

===============================================
the php log below:(note:the value of type is null)

[Tue May 22 09:34:43 2012] [error] [client 192.168.55.31] uploadFile=>Array
[Tue May 22 09:34:43 2012] [error] [client 192.168.55.31] name=>imageFileFromIPhoneApp.png
[Tue May 22 09:34:43 2012] [error] [client 192.168.55.31] type=>
[Tue May 22 09:34:43 2012] [error] [client 192.168.55.31] tmp_name=>/private/var/tmp/phpnbb3cf
[Tue May 22 09:34:43 2012] [error] [client 192.168.55.31] error=>0
[Tue May 22 09:34:43 2012] [error] [client 192.168.55.31] size=>868591

1 个答案:

答案 0 :(得分:0)

要使用POST上传图像,您必须将内容类型设置为application / octet-stream。这是我正在使用的代码:

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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=\"file\"; filename=\"attachment.png\"r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

编辑:这是我正在使用的PHP代码:

if (isset($_FILES["uploadedfile"]))
{
    echo $target_path = $target_path.basename($_FILES['uploadedfile']['name']); 
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
        echo "1: The file ".basename( $_FILES['uploadedfile']['name'])." has been uploaded";
    } else{
        echo "2: There was an error uploading the file, please try again!";
    }
}