iOS 上传文件

  NSString *boundry = @"boundry";//分节符

    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"服务器地址"]];

    [mutableRequest setHTTPMethod:@"POST"];

    NSMutableDictionary *head = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry],@"Content-Type",nil];

    [mutableRequest setAllHTTPHeaderFields:head];

    NSMutableString *mutableString = [[NSMutableString alloc] init];

    [mutableString appendFormat:@"--%@\r\n", boundry];

    [mutableString appendFormat: @"Content-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n\r\n"];//name + filename 自己看着来,其他就不要换了    

    NSMutableData *postData = [NSMutableData dataWithCapacity:[imageData length] + 512];

    [postData appendData:[mutableString dataUsingEncoding:NSUTF8StringEncoding]];

    [postData appendData:imageData];//插入要上传的文件数据(NSData)

    [postData appendData:

     [[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]];

    [mutableRequest setHTTPBody:postData];

    NSData *received = [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:nil error:nil];

你可能感兴趣的:(上传文件)