When uploading files using JavaScript and fetch, it's important to use FormData instead of JSON. This is because files (like images) need to be sent in a multipart/form-data encoding, which FormData handles automatically. Also, when using FormData, you should not set the Content-Type header manually; the browser sets it correctly for you, including the necessary boundaries.
In your current code, you're trying to send the image as part of a JSON payload, which doesn't work for file uploads. This is why you're seeing the error:
"The submitted data was not a file. Check the encoding type on the form."
Here's how you can modify your code to use FormData:
const form = document.getElementById('problemForm');
const title = document.getElementById('title');
const description = document.getElementById('description');
const image = document.getElementById('image');
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
form.addEventListener('submit', async (e) => {
e.preventDefault();
// Create a new FormData object
const formData = new FormData();
// Append the form fields and file to the FormData object
formData.append('title', title.value);
formData.append('description', description.value);
// For file inputs, use the `files` property
if (image.files.length > 0) {
formData.append('image', image.files[0]);
} else {
// Handle the case where no file was selected
console.error('No file selected for upload.');
return;
}
formData.append('found_by', '{{request.user.pk}}');
// Send the form data using fetch
const response = await fetch('http://127.0.0.1:8000/api/lost-item/', {
method: 'POST',
body: formData,
headers: {
// Do not set 'Content-Type' when sending FormData
'X-CSRFToken': csrfToken
}
});
// Handle the response
const data = await response.json();
console.log(data);
});
Explanation of Changes:
-
Use FormData Instead of JSON:
- We create a new
FormData object and append the form fields to it.
FormData automatically sets the correct encoding type (multipart/form-data) and handles file uploads properly.
-
Append the File Correctly:
- For file inputs, we access the selected file using
image.files[0].
- We append the file to
formData under the appropriate key ('image' in this case).
-
Do Not Set Content-Type Header Manually:
- When sending
FormData, you should not set the Content-Type header yourself. The browser sets it, including the boundary parameter that's necessary for multipart form data.
- Removing
'Content-Type': 'application/json' ensures the request is sent correctly.
-
Check if a File is Selected:
- Before appending the file, we check if a file is actually selected to prevent errors when no file is chosen.
Additional Tips:
Example HTML Form:
Make sure your HTML form and input fields are set up correctly. Here's an example:
<form id="problemForm">
<input type="text" id="title" name="title" placeholder="Title">
<textarea id="description" name="description" placeholder="Description"></textarea>
<input type="file" id="image" name="image">
<button type="submit">Submit</button>
</form>
Server-side (Django) Adjustments:
-
Serializers:
-
Ensure your serializer is set up to handle file uploads. For example:
from rest_framework import serializers
from .models import LostItem
class LostItemSerializer(serializers.ModelSerializer):
class Meta:
model = LostItem
fields = ['title', 'description', 'image', 'found_by']
-
Views:
- Ensure your view handles POST requests correctly. If using
ModelViewSet, it should handle POST by default.
By adjusting your code to use FormData, you should be able to successfully upload files along with other form data without encountering the error you mentioned.