iOS中如何向服务器发送Base64字符串?求助解决400错误
Hey there! Let's break down why you're hitting that 400 Bad Request error when sending images from your iOS app, and walk through fixes step by step.
Common Causes & Solutions
1. Base64 Encoding Includes Unwanted Line Breaks
Your current code uses NSDataBase64Encoding64CharacterLineLength, which inserts a line break every 64 characters. Many server-side parsers don't handle these line breaks correctly, leading to invalid request data.
Fix: Use an option that doesn't add line breaks. Replace your Base64 conversion code with:
NSData *imageData = UIImageJPEGRepresentation(chosenImage, 0.5); // Use 0 to avoid line breaks (safer for most servers) NSString *base64String = [imageData base64EncodedStringWithOptions:0];
2. JSON Serialization or Request Header Issues
A 400 error often means your request body is malformed. Let's check two key points here:
- Ensure your JSON is valid: Make sure the dictionary containing your Base64 string serializes correctly without errors.
- Set the correct Content-Type header: Servers expect
application/jsonfor JSON payloads.
Example of Correct JSON Setup:
-(void)temp { NSString *base64Str = [self base64return]; // Match the key name exactly to what your server API expects! NSDictionary *payload = @{@"image": base64Str}; // Serialize to JSON data NSError *jsonError; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payload options:0 error:&jsonError]; if (jsonError) { NSLog(@"JSON Serialization Failed: %@", jsonError.localizedDescription); return; } // Setup request with correct headers NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:yourServerURL]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:jsonData]; // Send request with NSURLSession... }
Pro tip: Mismatched key names (e.g., using @"img" instead of @"image" as your server expects) are a super common cause of 400 errors—double-check your API docs!
3. Request Body Size Exceeds Server Limits
Base64 encoding increases data size by ~33%, so even a compressed JPEG might be too large for your server's configured request limits.
Fixes:
- Lower the JPEG compression quality (try
0.3instead of0.5) to reduce file size. - Check your server's settings (e.g.,
max_post_sizefor Apache,client_max_body_sizefor Nginx) and adjust if possible.
4. Consider Sending Raw Image Data Instead of Base64
If your server supports it, sending the image as multipart/form-data (instead of embedding Base64 in JSON) is often more reliable and efficient. Here's a quick snippet:
NSData *imageData = UIImageJPEGRepresentation(chosenImage, 0.5); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:yourServerURL]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"UniqueBoundary12345"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; NSMutableData *body = [NSMutableData data]; // Add image part [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"uploaded.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body];
Final Checklist
- Test your Base64 string with an offline decoder to confirm it's valid (no line breaks, correctly decodes to an image).
- Use a tool like Postman to replicate the request manually—this helps isolate if the issue is with your app code or the server.
- Check your server logs for more specific error details (most servers log exactly why a 400 was returned).
内容的提问来源于stack exchange,提问作者Anshul Khare

