使用Angular4调用Django Rest API上传图片时出现400错误求助
Hey there! I’ve dealt with this exact issue before when working with Angular 4 and Django REST, so let’s walk through the most likely fixes to get your image uploads working:
1. Ensure You’re Using FormData Correctly (Angular Side)
The biggest mistake here is trying to send files as JSON instead of using multipart/form-data via FormData. Here’s how to adjust your code:
import { Component, OnInit } from '@angular/core'; import { Http, Headers } from '@angular/http'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private http: Http) {} onFileUpload(file: File, otherData: string) { // 1. Create FormData object const formData = new FormData(); // Append the image file (match the key 'image' to your Django serializer field name) formData.append('image', file, file.name); // Append any additional data you need to send formData.append('title', otherData); // 2. Set headers (DO NOT manually set Content-Type!) const headers = new Headers(); // headers.append('Content-Type', 'multipart/form-data'); ❌ Remove this line! // The browser automatically sets the correct Content-Type with boundary when using FormData // 3. Send the POST request this.http.post('http://your-django-api-url/upload/', formData, { headers: headers }) .subscribe( response => console.log('Upload successful:', response), error => console.error('Upload failed:', error) ); } ngOnInit() {} }
2. Configure Django REST to Handle File Uploads
Your Django backend needs proper setup to accept multipart form data:
a. Check Your Serializer
Make sure your model has an ImageField and the serializer includes it:
# serializers.py from rest_framework import serializers from .models import YourModel class YourModelSerializer(serializers.ModelSerializer): class Meta: model = YourModel fields = ('id', 'image', 'title') # 'image' must match the key in FormData
b. Update Your View Class
Add MultiPartParser and FormParser to handle file uploads:
# views.py from rest_framework import generics, parsers from .models import YourModel from .serializers import YourModelSerializer class ImageUploadView(generics.CreateAPIView): queryset = YourModel.objects.all() serializer_class = YourModelSerializer # Required to parse multipart/form-data requests parser_classes = (parsers.MultiPartParser, parsers.FormParser)
c. Verify Media File Settings
Ensure Django is configured to store and serve uploaded media files:
# settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Where files are stored MEDIA_URL = '/media/' # URL to access files
Add this to your project’s root urls.py to serve media files in development:
# urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import ImageUploadView urlpatterns = [ path('upload/', ImageUploadView.as_view(), name='image-upload'), # Other routes... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
3. Check for CORS Issues
If your Angular app and Django API are on different domains, you need to enable CORS:
- Install
django-cors-headers:
pip install django-cors-headers
- Update
settings.py:
INSTALLED_APPS = [ # ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # ... other middleware ] # Allow all origins in development (restrict to specific domains in production!) CORS_ALLOW_ALL_ORIGINS = True
4. Match Field Names Exactly
Double-check that the key you use in formData.append('image', ...) matches the field name in your Django model and serializer. A mismatch here will trigger a 400 error.
Start with these steps—most likely the issue is either an incorrect FormData setup or missing parsers in your Django view. Let me know if you still run into trouble after checking these!
内容的提问来源于stack exchange,提问作者Zuber




