簡體   English   中英

Django rest 框架不支持圖片上傳的媒體類型

[英]Django rest framework unsupported media type with image upload

這是我第一次嘗試將圖像上傳到 django rest 框架,我在前端使用 svelte,並使用 fetch api 進行請求。

我有一個我無法解決的錯誤。 所有包含圖像的請求都會返回不支持的媒體類型錯誤。

后端

我已將這些行添加到我的 settings.py

# Actual directory user files go to
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'mediafiles')

# URL used to access the media
MEDIA_URL = '/media/'

我的簡化視圖.py

@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
@parser_classes([FormParser, MultiPartParser])
def products(request):
if request.method == 'POST' and isPermitted(request.user, 'allow_edit_inventory'):
        serializer = ProductSerializer(data=request.data)
        serializer.initial_data['user'] = request.user.pk
        if serializer.is_valid():
            serializer.save()
            return Response({'message': "product added"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我的網址.py

from django.contrib import admin
from django.urls import path, include
from rest_framework.authtoken import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include("API.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

最后是我的 models.py

def product_images_upload_to(instance, filename):
    return 'images/{filename}'.format(filename=filename)
class Product(models.Model):
    name = models.CharField(max_length=200)
    image_url = models.ImageField(upload_to=product_images_upload_to, blank=True, null=True)

前端

我在 svelte 中的文件上傳組件,導出的圖像變量是在以下代碼的請求中使用的。

  export let avatar, fileinput, image;

    const onFileSelected = (e) => {
        image = e.target.files[0];
        let reader = new FileReader();
        reader.readAsDataURL(image);
        reader.onload = (e) => {
            avatar = e.target.result;
        };
    };

要求

export const addProduct = async (product) => {
    const fd = new FormData();
    fd.append("name", product.name);
    fd.append("image_url", product.image_url);

    const response = await fetch(`${URL}/products`, {
        method: "POST",
        headers: {
            "Content-Type": `multipart/form-data boundary=${fd._boundary}`,
            Authorization: `token ${localStorage.getItem("auth")}`
        },
        body: JSON.stringify(product),
    })
    return response
}

前端缺少分號

新的前端代碼:

export const addProduct = async (product) => {
    const fd = new FormData();
    fd.append("name", product.name);
    fd.append("image_url", product.image_url);

    const response = await fetch(`${URL}/products`, {
        method: "POST",
        headers: {
            "Content-Type": `multipart/form-data; boundary=${fd._boundary}`,
            Authorization: `token ${localStorage.getItem("auth")}`
        },
        body: JSON.stringify(product),
    })
    return response
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM