1

画像、動画、音声ファイルをサーバーにアップロードしたい。同様のトピックに関するこのスレッドを読みましたが、コードの流れを完全に理解できませんでした。最初にサンプル コードまたはチュートリアルを提案していただければ幸いです。次のコードを使用して、メディアなしでサーバーに接続しています

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *url =[[NSString alloc]initWithFormat:@"%@",[NetworkConstants getURL]];
NSURL *theURL =[NSURL URLWithString:url];
[url release];
NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:0.0f];
[theRequest setHTTPMethod:@"POST"];

NSString *theBodyString = [NSString stringWithFormat:@"json1=%@&userID=%@",jsonObject,[GlobalConstants getUID]];

NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:theBodyData];

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if (conn) {
    NSLog(@"Successful in sending sync");
}
else {
    NSLog(@"Failed Connection in sending sync");
}
[conn release];

コードのこの部分を編集して何かできれば、とても便利です。

どんな形の助けでも大歓迎です。

前もって感謝します!!

4

1 に答える 1

6

自分の質問に答えるのは非常に早いですが、解決策を得たので、ここに追加することを考えました。

上記のコードには、次の変更が必要です

        NSData *imageData = UIImageJPEGRepresentation(attachedImage.image, 90);
        NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [theRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];


        NSMutableData *theBodyData = [NSMutableData data];
        [theBodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [theBodyData appendData:[@"Content-Disposition: form-data; name= \"server_value_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [theBodyData appendData:[yourString dataUsingEncoding:NSUTF8StringEncoding]];
        //this appends the image data
        [theBodyData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [theBodyData appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"image\"; filename=\"1.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [theBodyData appendData:[[NSString stringWithString:@"Content-Type: image/jpg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [theBodyData appendData:[NSData dataWithData:imageData]];
        [theBodyData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [theRequest setHTTPBody:theBodyData];

そして、残りは質問と同じままです。

マルチパート リクエストを送信する際に、サーバーが必要とするすべてのパラメーターを境界内で使用する必要があり、すべてのパラメーターを個別の境界内で送信する必要があることを覚えておく必要があります。

これが他の人にも役立つことを願っています。

:)

于 2011-03-09T08:02:28.507 に答える