【问题标题】:Django REST: Files\Images UploadingDjango REST:文件\图像上传
【发布时间】:2019-09-01 06:07:39
【问题描述】:

我想使用 Vue.js 和 Django-rest 上传图像。并且几乎没有问题。

我尝试使用 put 请求(如 docs 中)和 FileUploadParser,但收到错误:

detail: "Missing filename. Request should include a Content-Disposition header with a filename parameter.

如果我的标题是这样的:

'Content-type':'multipart/form-data',
                'filename': 'file'

Django 将请求注册为 OPTIONS,而不是 put,所以我的 put 函数没有被调用。

我的序列化器:

class ImagesSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Images
        fields = ('image',)

我的看法:

class ImagesViewSet(APIView):
    parser_classes = (FileUploadParser,)

    def get(self, request):
        images = Images.objects.all()
        serializer = ImagesSerializer(images, many=True)
        return Response(serializer.data)


    def put(self, request, filename, format=None):
        image = request.data['image']

        Images.objects.create(
            image=image
        )
        return Response(status=204)

我的 Vue.js 请求:

import axios from 'axios';

export default {
  name: 'App',
  data(){
    return {
        name: '',
        image: '',
        description: '',
        price: '',
        files: false,
        }
    },
    methods: {
        onFileChange(e) {
            console.log('works');
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length)
                return;
            this.createImage(files[0]);
        },
        createImage(file) {
            var image = new Image();
            var reader = new FileReader();
            var vm = this;

            reader.onload = (e) => {
                vm.image = e.target.result;
            };
            reader.readAsDataURL(file);
        },
        createNewProduct(){

        const config = {
            headers: {
                'Content-type':'multipart/form-data',
                'filename': 'file'
            }
        }

        let formData = new FormData();
        formData.append('image', this.image);

        axios.put('http://127.0.0.1:8000/images/',{
            formData
        }, config).then(response => {
            console.log('Success');
            this.$router.push('/')
        }, response => {
            console.log('FAIL');
        });
        } 
    }
}

我做错了什么,或者我错过了什么?

【问题讨论】:

    标签: python django rest vue.js django-rest-framework


    【解决方案1】:

    Django REST framework 中的文件上传与 django 中的 multipart/form 中的文件上传相同。

    你可以使用 curl 来测试它:

    curl -X POST -H "Content-Type:multipart/form-data" -u {username}:{password} \
    -F "{field_name}=@{filename};type=image/jpeg" http://{your api endpoint}
    

    您可以尝试在 stackoverflow 上找到解决方案

    link

    【讨论】:

    • 这不是 DRF 的解决方案。我知道它在 Django 中是如何工作的,但在 DRF 中它有点不同。
    • 附上的源码链接有解决你问题的办法
    【解决方案2】:

    除了 Content-Type 标头之外,您还需要添加一个 content-disposition 标头,如下所示:

    headers: {
        'Content-type':'multipart/form-data',
        'Content-Disposition': 'attachment; filename=file',
        'filename': 'file'
    }
    

    【讨论】:

    • 同样的问题:即使 Content-Disposition 请求注册为选项
    • 不确定 Nancy Mooree 是否已经回答了您的问题,但 OPTIONS 请求是 PUT/POST 请求之前的标准请求。它被称为防止 CORS 伪造的预检请求,您可以在此处阅读更多内容:developer.mozilla.org/en-US/docs/Web/HTTP/CORS 话虽如此,我会再次尝试该请求,但删除您的“文件名”密钥。试试headers: { 'Content-Type':'multipart/form-data', 'Content-Disposition': 'attachment; filename=file' } 希望这应该可行。
    • OPTIONS请求得到响应后,浏览器会自动发送PUT请求。这应该由 djangorestframework 处理,根本不需要您处理 OPTIONS 请求。
    猜你喜欢
    • 2014-10-16
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2011-03-21
    • 2016-03-23
    • 2018-03-12
    相关资源
    最近更新 更多