要将图片从React前端上传到Django后端,你需要理解以下几个基础概念:
<input type="file">
来允许用户选择文件。FormData
对象来封装文件数据。import React, { useState } from 'react';
import axios from 'axios';
const FileUpload = () => {
const [file, setFile] = useState(null);
const handleFileChange = (event) => {
setFile(event.target.files[0]);
};
const handleUpload = async () => {
const formData = new FormData();
formData.append('file', file);
try {
const response = await axios.post('http://your-django-backend-url/upload/', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log(response.data);
} catch (error) {
console.error(error);
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload</button>
</div>
);
};
export default FileUpload;
MEDIA_URL
和MEDIA_ROOT
来处理上传的文件。# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from .views import upload_file
urlpatterns = [
path('upload/', upload_file, name='upload_file'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import os
@csrf_exempt
def upload_file(request):
if request.method == 'POST':
file = request.FILES['file']
file_path = os.path.join('media', file.name)
with open(file_path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
return JsonResponse({'message': 'File uploaded successfully'}, status=200)
return JsonResponse({'error': 'Invalid request'}, status=400)
django-cors-headers
库并配置。pip install django-cors-headers
# settings.py
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = True # 生产环境中建议指定具体的域名
# settings.py
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024 # 10MB
FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024 # 10MB
@csrf_exempt
装饰器(不推荐在生产环境中使用)。通过以上步骤,你应该能够成功地将图片从React前端上传到Django后端。如果遇到其他问题,请检查日志和错误信息,逐步排查问题所在。
领取专属 10元无门槛券
手把手带您无忧上云