ios使用http來上傳圖片實現方法

來源:互聯網
上載者:User

標籤:des   style   http   color   使用   os   io   檔案   

if (parameters) {
        
        int genderNumber = 1;
        self.token = loginToken;
        self.personPK = kidPK;
        self.personName = personNameL;
        self.personNickName = nickNameL;
        self.gender = genderL;
        self.birthday = birthdayL;
        self.imageData = imageL;
        self.imageName = imageNameL;
        if ([self.gender isEqualToString:@"女"]) {
            
            genderNumber = 2;
        }
        
        [parameters setValue:self.token forKey:@"token"];
        [parameters setValue:self.personPK forKey:@"personPk"];
        [parameters setValue:self.personName forKey:@"person.name"];
        [parameters setValue:self.personNickName forKey:@"person.nickname"];
        [parameters setValue:[NSString stringWithFormat:@"%d", genderNumber] forKey:@"person.gender"];
        [parameters setValue:self.birthday forKey:@"birthday"];
        [parameters setValue:self.personNickName forKey:@"turFileFileName"];
        //[parameters setValue:image forKey:@"turFile"];
        
        
    }
    
    self.LoadStatus = LOADING;
    self.strURL = tmp;
    NSLog(@"the url is %@",self.strURL);
    self.activeDownload = [NSMutableData data];
    
    
    //分界線的標識符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根據url初始化request
    NSMutableURLRequest* requestL = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.strURL]
                                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                        timeoutInterval:30];
    //分界線 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //結束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //得到圖片的data
    // self.imageData = UIImagePNGRepresentation(image);
    //http body的字串
    NSMutableString *body=[[NSMutableString alloc]init];
    //參數的集合的所有key的集合
    NSArray *keys= [parameters allKeys];
    
    //遍曆keys  注意這個除去了data類型只是包含了string類型的
    for(int i=0;i<[keys count];i++)
    {
        //得到當前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic,說明value是字元類型,比如name:Boris
        //添加分界線,換行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加欄位名稱,換2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        //添加欄位的值
        [body appendFormat:@"%@\r\n",[parameters objectForKey:key]];
        
    }

    //注意這裡的turFile其實就是要上傳的file的欄位名字
    ////添加分界線,換行
    [body appendFormat:@"%@\r\n",MPboundary];
    //聲明pic欄位,檔案名稱為boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"turFile\"; filename=\"boris.jpg\"\r\n"];
    //聲明上傳檔案的格式
    [body appendFormat:@"Content-Type: image/jpeg\r\n\r\n"]; //這裡因為之前壓縮產生的是jpg類型的圖片所以需要表明jpeg,如果是png就是png
    
    //聲明結束符:--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //聲明myRequestData,用來放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //將body字串轉化為UTF8格式的二進位
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //將image的data加入
    [myRequestData appendData:self.imageData];
    //加入結束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //設定HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //設定HTTPHeader
    [requestL setValue:content forHTTPHeaderField:@"Content-Type"];
    //設定Content-Length
    [requestL setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //設定http body
    [requestL setHTTPBody:myRequestData];
    //http method
    [requestL setHTTPMethod:@"POST"];
    
    //建立串連,設定代理
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:requestL delegate:self];
    self.loadConnection = conn;
    [conn release];
    
    if (self.loadConnection != nil)
    {
        [self.loadConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    }

壓縮的方法實現:

-(void)compraseImage
{
    UIImage *largeImage = self.pictureViewUpload.image;
    
    double compressionRatio = 1;
    int resizeAttempts = 5;
    
    NSData * imgData = UIImageJPEGRepresentation(largeImage,compressionRatio);
    
    //NSLog(@"Starting Size: %i", [imgData length]);
    
    //Trying to push it below around about 0.4 meg
    while ([imgData length] > 400000 && resizeAttempts > 0) {
        resizeAttempts -= 1;
        
        //NSLog(@"Image was bigger than 400000 Bytes. Resizing.");
        //NSLog(@"%i Attempts Remaining",resizeAttempts);
        
        //Increase the compression amount
        compressionRatio = compressionRatio*0.5;
        //NSLog(@"compressionRatio %f",compressionRatio);
        //Test size before compression
        //NSLog(@"Current Size: %i",[imgData length]);
        imgData = UIImageJPEGRepresentation(largeImage,compressionRatio);
        
        //Test size after compression
        //NSLog(@"New Size: %i",[imgData length]);
    }
    
    //Set image by comprssed version
    //self.pictureView.image = [UIImage imageWithData:imgData];
    
    //Check how big the image is now its been compressed and put into the UIImageView
    
    // *** I made Change here, you were again storing it with Highest Resolution ***
    NSData *endData = UIImageJPEGRepresentation(largeImage,compressionRatio);
    //NSLog(@"Ending Size: %i", [endData length]);
    
    /* NSString *path = [self createPath:@"myImage.jpg"];
     NSLog(@"%@",path);
     [endData writeToFile:path atomically:YES];*/
    
    [self startUploadingRequestWithData:endData andImage:self.pictureViewUpload.image];
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.