2016-07-15 21 views
-1

// webteamコードマルチパートリクエストとしてiOSにイメージアレイをアップロードするには?アップロード画像のため

するvar hoardingjson = { _id:ID、 populationincomegroup:incomeGroupArray、 availablebydate:availDate、 タイトル:タイトル、 説明:DESC、 onemonthprice:oneMprice、 threemonthsprice。 threeMprice、 sixmonthsprice:sixMprice、 oneyearprice:oneYrprice、 地域:地域、 streetname:streetName、 trafficdensity:trafficDensity、 populationcategory:populati onDensity、 ownernameに:ownernameに、 モバイル:モバイル、 leaseowner:currenrOwnerName、 長さ:hoardingWidth、 幅:hoardingHeight、 緯度:緯度、 経度:LON、 registereddate:currentTimestamp、 CREATEDATE: ""、 updatedate : ""、 ステータス: ""、 オーナーID:ownerid };

var form_data = new FormData(); 
var imageCount = document.getElementById("editImages").files.length; 
for (i = 0; i < imageCount; i++) { 
    form_data.append("file", document.getElementById("editImages").files[0]); 
} 
var xhr = new XMLHttpRequest(); 
xhr.open("POST", server_url + "UpdateHoarding", true); 
xhr.setRequestHeader("hoardingjson", JSON.stringify(hoardingjson)); 
xhr.send(form_data); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4) { 
     if (xhr.status === 200) { 
      success = true; 
      $("#updateHoardingModal").modal("hide"); 
      alert("Hoarding is updated successfully"); 
      location.href = "home.jsp"; 
     } 
    } 
} 

IOSコード:

NSStringの* jsosSt = [自己strOfthedata]。

UIImage *imageOne = [UIImage imageNamed:@"edit.png"]; 
NSData *imageData1 = UIImageJPEGRepresentation(imageOne,0.6f); 
NSString *fileName1 = [NSString stringWithFormat:@"%ld%c%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a']; 

NSDictionaryの* paramsは= @ {@ "トークン":appdeligate.userInf.tokenId、 "hoardingjson" @:[自己strOfthedata]}。

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"URL/CreateHoarding" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 

    [formData appendPartWithFileURL:[NSURL fileURLWithPath:savedImagePath] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; 



} error:nil]; 


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

NSMutableString *strParams = [[NSMutableString alloc]init]; 
for (NSString *key in [params allKeys]) { 
    [strParams appendFormat:@"%@=%@", key, params[key]]; 
    [strParams appendString:@"&"]; 
} 

[strParams deleteCharactersInRange:NSMakeRange([strParams length]-1, 1)]; 
[request setHTTPBody:[strParams dataUsingEncoding:NSUTF8StringEncoding]]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 




NSURLSessionUploadTask *uploadTask; 
uploadTask = [manager 
       uploadTaskWithStreamedRequest:request 
       progress:^(NSProgress * _Nonnull uploadProgress) { 
        // This is not called back on the main queue. 
        // You are responsible for dispatching to the main queue for UI updates 
        dispatch_async(dispatch_get_main_queue(), ^{ 
         //Update the progress view 
         [progressView setProgress:uploadProgress.fractionCompleted]; 
         NSLog(@"%f",uploadProgress.fractionCompleted); 
        }); 
       } 
       completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
        if (error) { 
         NSLog(@"Error: %@", error); 
        } else { 
         NSLog(@"%@ %@", response, responseObject); 
        } 
       }]; 

[uploadTask resume]; 
+0

あなたはそれがために要求され、この[質問](http://stackoverflow.com/questions/37941306/download-one-file-at-a-time-using-afnetworking/)を見て持っていますあなたはアップロードのために同じものを実装する必要があります –

+0

AFNetworkを使用していますか、正しい –

+0

はいAfnetworking 3ですが、イメージフォームの部分は受信していませんが、jsonは[request setValue:@ "application/x- form-urlencoded "forHTTPHeaderField:@" content-type "]; jsonでも画像をサーバーに正しく受信するために必要なものが得られています –

答えて

0

------------これが使用している。ここ

-(void)UploadImagewithUrl:(NSString *)serviceURL 
       withJson:(NSString *)jsonStr 
       withtoken:(NSString *)Token_id 
      withImageArray:(NSArray *)imageURlArray 
       callback:(SuccessCallback)callback 
      failerCallback:(FailureCallback)failercallback { 

NSString *baserl=[NSString stringWithFormat:@"%@?token=%@&hoardingjson=%@",serviceURL,Token_id,jsonStr]; 
baserl = [baserl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSString *lineEnd = @"\r\n"; 
NSString* twoHyphens = @"--"; 
NSString* boundary = @"*****"; 
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:baserl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 

    [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    for (int i=0; i<imageURlArray.count; i++) { 

     NSData *imageData = [[NSFileManager defaultManager] contentsAtPath:[imageURlArray objectAtIndex:i]]; 
     NSString *fileName = [NSString stringWithFormat:@"%ld%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a']; 


     [formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:@"twoHyphens"]; 
     [formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding] 
            name:@"boundary"]; 
     [formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding] 
            name:@"lineEnd"]; 
     [formData appendPartWithFileData:imageData 
            name:@"file" 
           fileName:fileName 
           mimeType:@"image/jpeg"]; 
    } 

    [formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding] name:@"lineEnd"]; 
    [formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:@"twoHyphens"]; 
    [formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding] 
           name:@"boundary"]; 
    [formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding] 
           name:@"lineEnd"]; 


} error:nil]; 


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
NSURLSessionUploadTask *uploadTask; 
uploadTask = [manager 
       uploadTaskWithStreamedRequest:request 


       progress:^(NSProgress * _Nonnull uploadProgress) { 
        // This is not called back on the main queue. 


        [SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"Uploading"]; 

        if (uploadProgress.fractionCompleted==1) 
        { 
         [SVProgressHUD dismiss]; 
        } 

        // You are responsible for dispatching to the main queue for UI updates 
        dispatch_async(dispatch_get_main_queue(), ^{ 
         //Update the progress view 
         [progressView setProgress:uploadProgress.fractionCompleted]; 


        NSLog(@"---response---- %@",uploadProgress); 

        }); 


       } 
       completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 


        if (error) { 
         failercallback([NSString stringWithFormat:@"%ld",error.code],@"failer"); 
         NSLog(@"Error: %@", error); 

        } else { 

         callback(YES,responseObject); 
         NSLog(@"%@ %@", response, responseObject); 
       } 
       }]; 

[uploadTask resume]; 
} 
0

---------------私のために働いています

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]]; 
manager.responseSerializer = [AFJSONResponseSerializer serializer]; 
manager.requestSerializer = [AFJSONRequestSerializer serializer]; 

[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
{ 
    //do not put image inside parameters dictionary as I did, but append it! 
    [formData appendPartWithFileData:nsdataFromBase64String name:@"" fileName:@"" mimeType:@"image/jpeg"]; 

} 
success:^(NSURLSessionDataTask *task, id responseObject) 
{ 
    //here is place for code executed in success case 
} 
failure:^(NSURLSessionDataTask *task, NSError *error) 
{ 
    //here is place for code executed in error case 
}]; 
  1. stringURLをAFNetworkingすると、アップロード/画像を送りたいURLです。
  2. NSData * nsdataFromBase64String = [NSData alloc] initWithBase64EncodedString:pBytesオプション:0]; ここで、nsdataFromBase64Stringはbase64文字列へのイメージ変換であり、サーバー上でこれをデコードします。
    1. pngが必要な場合は、MIMEタイプを確認してください。
関連する問題