duanjiao8871 2013-11-16 12:44
浏览 32

将附加的帖子数据与jpeg一起添加到NSURLConnection

I am having trouble uploading both a file and additional simple post information when using NSURLConnection. I know there are many questions about this already but none of them seem to answer my question, so i apologise in advance if it has been answered, and if you could point me in the right direction, that would be great.

I am using this code to upload a jpeg chosen form camera roll:

    NSData *imageData = UIImageJPEGRepresentation(image, 50);

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

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename='profileImage.jpg'rn",usernameString] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-streamrnrn" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // setting the body of the post to the reqeust
    [request setHTTPBody:body];

    // now lets make the connection to the web
    registerConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [registerConnection start];

However i also need to send 2 more values as post information such as funcID=1 and username=sampleUsername so my php code knows exactly what to do with the file. I have attempted to appendData to the current body, such as:

[body appendData:[[NSString stringWithFormat:@"funcCode=1&username=%@",
                     usernameString] dataUsingEncoding:NSUTF8StringEncoding]]; 

but it doesnt work, and i am not sure why exactly.

Any help is much appreciated, thanks!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 对于相关问题的求解与代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料
    • ¥15 使用R语言marginaleffects包进行边际效应图绘制