简体   繁体   English

Django rest 框架不支持图片上传的媒体类型

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

this is my first time trying to upload image to django rest framework, i am using svelte for my front end and using the fetch api for requests.这是我第一次尝试将图像上传到 django rest 框架,我在前端使用 svelte,并使用 fetch api 进行请求。

i am have an error that i cannot solve.我有一个我无法解决的错误。 all requests containing images return an unsupported media type error.所有包含图像的请求都会返回不支持的媒体类型错误。

Back End后端

i have added these line to my settings.py我已将这些行添加到我的 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/'

my simplified views.py我的简化视图.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)

my urls.py我的网址.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)

and finally my models.py最后是我的 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)

Front End前端

my file upload component in svelte, the exported image variable is what get used in the request in the following code.我在 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;
        };
    };

request要求

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
}

was missing a semicolon in the frontend前端缺少分号

new front end code:新的前端代码:

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