Multipart/form – the data request

What multipart/form-data actually means is not going to be explained here, but there are a lot of explanations on the Internet, so let’s just look at the code. When AFN and other network frameworks cannot meet their own needs, they often need to find a method from the most primitive place.

Form request header:

Content-Type: multipart/form-data; Boundary =${boundary} //bound = uuid

Form request body (upload image file here, convert image to data) :

NSString*boundary = [[NSUUID UUID]UUIDString]; // A random string used as a separator

NSString*BoundarySingle=[[NSString alloc]initWithFormat:@”–%@”,boundary];

// End character –tsunamierFileFlag–

NSString*endBoundary=[[NSString alloc]initWithFormat:@”\r\n%@–“,BoundarySingle];

NSMutableData*data = [[NSMutableData alloc]init];

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

for(inti =0; i < [requestHeader.allKeyscount]; i++)

{

[str appendFormat:@”%@\r\n”,BoundarySingle];

[str appendFormat:@”Content-Disposition: form-data; name=\”%@\”\r\n”,[requestHeader.allKeysobjectAtIndex:i]]; // This is the parameter name

[str appendFormat:@”Content-Type: text/plain;charset=UTF-8\r\n”];

[str appendFormat:@”Content-Transfer-Encoding:8bit\r\n\r\n”];

[str appendFormat:@”%@\r\n”, [requestHeaderobjectForKey:[requestHeader.allKeysobjectAtIndex:i]]]; // Add parameter values

// All other parameters except the file are concatenated

[str appendFormat:@”%@\r\n”,BoundarySingle];

[str appendFormat:@”Content-Disposition: form-data; name=\”noticefile\”;filename=\”%@.jpg\”\r\n”,boundary]; // Noticefile is the file parameter name

[str appendFormat:@”Content-Type:\r\n”];

[str appendFormat:@”Content-Transfer-Encoding:binary\r\n\r\n”];    

[data appendData:[strdataUsingEncoding:NSUTF8StringEncoding]];

[data appendData:fileData]; //fileData converts data to files

[data appendData:[endBoundarydataUsingEncoding:NSUTF8StringEncoding]]; // At this point, all request bodies are concatenated

Send a request:

NSMutableURLRequest*request = [[NSMutableURLRequest alloc]initWithURL:[NSURLURLWithString:[selfsendMessageUrl]]];

NSString*ContentType=[[NSString alloc]initWithFormat:@”multipart/form-data; boundary=%@;charset=UTF-8″,boundary];

[request setValue:ContentTypeforHTTPHeaderField:@”Content-Type”];

[request setHTTPBody:data];

[request setHTTPMethod:@”POST”];

request.timeoutInterval=40;

NSURLSession*session = [NSURLSessionsharedSession];

NSURLSessionDataTask*dataTask=[session dataTaskWithRequest:requestcompletionHandler:^(NSURLResponse*_Nonnullresponse,id_NullableresponseObject,NSError*_Nullabl eerror) {

}];

[dataTaskresume];

In multipart/form-data requests, note that the Encoding of common parameters and file parameters must be connected to the server.