如何在字典中将图像和其他参数发布为multipart / form-data - HTML body?

时间:2021-05-03 19:47:10

how to send name, email and image as multipart data to server? Following is my block of code ' func postRequest( params : NSMutableDictionary, url : String, onCompletion : (succeeded : Bool, data : NSDictionary, status_code : Int) -> ()) {

如何将名称,电子邮件和图像作为多部分数据发送到服务器?以下是我的代码块'func postRequest(params:NSMutableDictionary,url:String,onCompletion :(成功:Bool,数据:NSDictionary,status_code:Int) - >()){

    var JSONSerializationError : NSError?
    let boundary = generateBoundaryString()

    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    request.HTTPMethod = "POST"

    var profilePicData: AnyObject? = params.valueForKey(UserStatus().profilePicData)
    params.removeObjectForKey(UserStatus().profilePicData)
    println("params: \(params)")
    var body : NSMutableString = NSMutableString()

    if profilePicData == nil {
        println("Image is not uploading")
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &JSONSerializationError)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

    }else{
        println("Image is uploading")
         var TWITTERFON_FORM_BOUNDARY:String = "AaB03x"
        var MPboundary:String = "--\(TWITTERFON_FORM_BOUNDARY)"
        var endMPboundary:String = "\(MPboundary)--"

        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData

            for (key, value) in params {
                println("Key: \(key) Value: \(value)")
                body.appendFormat("\(MPboundary)\r\n")
                body.appendFormat("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendFormat("\(value)\r\n")
            }

        var filename = "file"
        body.appendFormat("%@\r\n",MPboundary)
        body.appendFormat("Content-Disposition: form-data; name=\"\(filename)\"; filename=\"profilePic.png\"\r\n")
        body.appendFormat("Content-Type: image/png\r\n\r\n")
        var end:String = "\r\n\(endMPboundary)"

        var myRequestData:NSMutableData = NSMutableData();
        myRequestData.appendData(body.dataUsingEncoding(NSUTF8StringEncoding)!)
        myRequestData.appendData(profilePicData as! NSData)
        println("after for loop1 ")
        myRequestData.appendData(end.dataUsingEncoding(NSUTF8StringEncoding)!)
        var content:String = "multipart/form-data; boundary=\(TWITTERFON_FORM_BOUNDARY)"
        request.setValue(content, forHTTPHeaderField: "Content-Type")
        request.setValue("\(myRequestData.length)", forHTTPHeaderField: "Content-Length")
        request.HTTPBody = myRequestData

        println("after for loop 2")
    }

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response : NSURLResponse!, data : NSData!, error : NSError!) -> Void in
        let HTTPResponse = response as! NSHTTPURLResponse

        println("URL Data: \(data)")
        println("Response Code: \(HTTPResponse.statusCode)")

        var jsonResult : NSDictionary!

        if (error != nil) {
            println("NetworkHandler Post Request Error: " + error.localizedDescription)
            onCompletion(succeeded: false, data: jsonResult, status_code: HTTPResponse.statusCode)
        } else {
            var JSONError: NSError?
            jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &JSONError) as! NSDictionary

            if (JSONError != nil) {
                println("NetworkHandler JSONSerialization Error: " + JSONError!.localizedDescription)
                onCompletion(succeeded: false, data: jsonResult, status_code: HTTPResponse.statusCode)
            } else {
                println("JSON Result: \(jsonResult)")
                onCompletion(succeeded: true, data: jsonResult, status_code: HTTPResponse.statusCode)
            }
        }
    }
}

' App is crashed on line: NSURLConnection.sendAsynchronousRequest.... with error message: fatal error: unexpectedly found nil while unwrapping an Optional value Params is NSMutableDictionary contains name, email and image

'应用程序崩溃在线:NSURLConnection.sendAsynchronousRequest ....带错误消息:致命错误:在展开可选值时意外发现nil Params是NSMutableDictionary包含名称,电子邮件和图像

1 个解决方案

#1


Using AFNetworking 3.0

Objective-C

使用AFNetworking 3.0 Objective-C

-(void)requestToUploadImageWithURL:(NSString *)url imageData:(NSData *)imageData  parameterDictionary:(NSMutableDictionary *)datat requestType:(NSString *)reqType handler:(NSObject *)handler selector:(SEL)selector{

//    reqType is POST or GET
    NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
    [data setObject:imageData forKey:@"fileStream"];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

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

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:reqType URLString:[NSString stringWithFormat:@"%@",url] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
//    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; //application/octet-stream
[req setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
if (data != nil) {
    NSLog(@"Data is not nil");
       [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

}else{
    NSLog(@"Data is nil");
}



[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        //            NSLog(@"Reply JSON: %@", responseObject);
        [handler performSelector:selector withObject:responseObject];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //blah blah
        }
    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
        [handler performSelector:selector withObject:responseObject];
    }
}] resume];

}

#1


Using AFNetworking 3.0

Objective-C

使用AFNetworking 3.0 Objective-C

-(void)requestToUploadImageWithURL:(NSString *)url imageData:(NSData *)imageData  parameterDictionary:(NSMutableDictionary *)datat requestType:(NSString *)reqType handler:(NSObject *)handler selector:(SEL)selector{

//    reqType is POST or GET
    NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
    [data setObject:imageData forKey:@"fileStream"];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

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

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:reqType URLString:[NSString stringWithFormat:@"%@",url] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
//    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; //application/octet-stream
[req setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
if (data != nil) {
    NSLog(@"Data is not nil");
       [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

}else{
    NSLog(@"Data is nil");
}



[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (!error) {
        //            NSLog(@"Reply JSON: %@", responseObject);
        [handler performSelector:selector withObject:responseObject];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //blah blah
        }
    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
        [handler performSelector:selector withObject:responseObject];
    }
}] resume];

}