Android端Multipart图片上传失败求助(Flask服务端)
Hey there! Let's figure out why your Flask upload is failing in your app but working perfectly in Postman. Since Postman can successfully send the request, the problem is almost definitely in how your app is constructing the multipart/form-data request. Here are the key checks and fixes to try:
Flask relies entirely on matching the field names you defined in your server route. If your app uses a slightly different name (even a capitalization difference!), the server won't pick up the data, leading to that vague "Error during upload" message.
- For example: If your Flask code uses
request.files['image_file']andrequest.form['image_dim_width'], make sure your app uses those exact keys when attaching the file and form data. - Don't mix up form fields and file fields: Dimensions (width/height) should be sent as regular form data, not as file attachments.
When sending multipart data, never manually hardcode the Content-Type: multipart/form-data header with a boundary. Most HTTP libraries (like requests in Python, Axios in JS, or OkHttp in Kotlin) automatically generate the correct boundary and set the header for you. If you hardcode it, you'll almost certainly end up with a mismatched boundary that the server can't parse.
Bad example (Python requests):
# Don't do this! headers = {'Content-Type': 'multipart/form-data'} response = requests.post(UPLOAD_URL, files=image_data, data=dimensions, headers=headers)
Good example:
# Let the library handle the boundary response = requests.post(UPLOAD_URL, files=image_data, data=dimensions)
If your app is reading the image file as a string instead of raw bytes, the server won't be able to process it. Here's how to do it right in common environments:
Mobile (Kotlin/OkHttp):
val imageFile = File(imagePath) val imageRequestBody = imageFile.asRequestBody("image/jpeg".toMediaTypeOrNull()) val imagePart = MultipartBody.Part.createFormData("image_file", imageFile.name, imageRequestBody) // Add dimension fields val widthPart = RequestBody.create(MediaType.parse("text/plain"), imageWidth.toString()) val heightPart = RequestBody.create(MediaType.parse("text/plain"), imageHeight.toString()) val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addPart(imagePart) .addFormDataPart("image_width", imageWidth.toString()) .addFormDataPart("image_height", imageHeight.toString()) .build()
Web Frontend (JavaScript/Axios):
const formData = new FormData(); // imageFile should be a File object from an <input type="file"> formData.append('image_file', imageFile); formData.append('image_width', imageWidth.toString()); formData.append('image_height', imageHeight.toString()); axios.post('/upload', formData, { // Axios can auto-detect this, but it's safe to include headers: { 'Content-Type': 'multipart/form-data' } }) .then(res => console.log(res)) .catch(err => console.error(err));
Capture the full request your app sends (headers, form fields, file metadata) and compare it to the working Postman request. Tools like Charles Proxy or Wireshark can help you inspect both requests side-by-side.
You can also add debug logging in your Flask route to see what the server is actually receiving:
from flask import Flask, request app = Flask(__name__) @app.route('/upload', methods=['POST']) def handle_upload(): print("Received form fields:", request.form) print("Received files:", request.files) # Your existing upload logic here
Flask has a default maximum upload size (around 16MB). If your image exceeds this, the server will silently reject the request. Update your Flask config to increase the limit if needed:
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024 # 32MB limit
Add error handling to catch this case explicitly:
@app.errorhandler(413) def too_large(error): return "Uploaded file is too large. Max size is 32MB.", 413
Once you fix these common pitfalls, your app should be able to upload the data smoothly just like Postman does!
内容的提问来源于stack exchange,提问作者Đorđe Ivanović

