如何通过React-Redux-Saga结合Node.js/Multer实现带图片的项添加
The core issue here is that you're trying to serialize FormData into JSON, which doesn't work—JSON can't represent binary file data. Postman sends requests as multipart/form-data (the correct format for file uploads), but your React code is wrapping the file data in a JSON object that your Node.js backend can't parse for files. Here's how to fix this step by step:
1. Correctly Build FormData in Your React Component
Instead of nesting FormData inside a JSON object, create a single FormData instance that includes all your form fields and files. Make sure to use the field name images (matching your multer setup) for file uploads:
handleSubmit = e => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { const { fileList } = this.state; const formData = new FormData(); // Add all regular form fields to FormData Object.entries(values).forEach(([key, value]) => { formData.append(key, value); }); // Add each file using the field name "images" (matches multer's .array("images")) fileList.forEach(file => { formData.append("images", file); }); // Pass the FormData directly to your action this.props.createItem(formData); } }); };
2. Update Your Saga to Send FormData Properly
Remove JSON.stringify from your request body—send the raw FormData object directly. Also, don't manually set the Content-Type header; the browser will automatically set it to multipart/form-data with the correct boundary identifier:
{ let itemData = yield select(makeSelectPostItemData()); const token = yield select(makeSelectToken()); console.log(itemData, "itemData"); const response = yield call(request, `/item`, { method: "POST", headers: { Authorization: `${token}` // No Content-Type header needed here }, body: itemData // Send FormData directly, not JSON }); const successMessage = "Item saved successfully!"; yield put(postItemSuccess(response, successMessage)); }
3. Verify Node.js Backend Setup
Your existing multer code looks correct, but double-check that:
- The multer
arraymethod uses"images"(which it does:.array("images")) - You're handling the request after multer processes the files (your current code does this)
Why This Works
FormDatais the standard way to send file data via HTTP, matching how Postman constructs requests.- By avoiding JSON serialization, you preserve the binary file data so multer can parse it correctly.
- The browser automatically sets the necessary
multipart/form-dataheader with a boundary, which tells your backend how to split the request into fields and files.
内容的提问来源于stack exchange,提问作者Sujan Joshi

