简体   繁体   English

如何使用 Axios 将文件上传到 Django REST 框架 API 和反应钩子形式?

[英]How to upload file to Django rest framework API using Axios and react hook form?

I have created an API using Django Rest Framework.我使用 Django Rest Framework 创建了一个 API。 It has an image uploading option.它有一个图像上传选项。 But I can not upload the file.但我无法上传文件。 I am using Axios for API calls and react hook form for form handling.我使用 Axios 进行 API 调用,并使用钩子表单进行表单处理。 I am posting the code below for better understanding.我发布下面的代码以便更好地理解。

Django: Model:姜戈:型号:

class BlogModel(models.Model):
    user = models.ForeignKey(user_model.User, on_delete=models.CASCADE, related_name="user_blog")
    blogtitle = models.CharField(max_length=250)
    blogcontent = models.TextField()
    blogimg = models.ImageField(upload_to="blog_image", blank=True)
    slug = models.SlugField(max_length=250, unique=True)
    tags = models.ManyToManyField(BlogTagsModel, related_name='blog_tags', blank=True, null=True)
    published_date = models.DateTimeField(auto_now_add=True)
    edit_date = models.DateTimeField(auto_now=True)

Serializer串行器

class BlogSerializer(serializers.ModelSerializer):
    class Meta:
        model = blog_model.BlogModel
        fields = '__all__'
        extra_kwargs = {
            'user': {'read_only': True},
            'slug': {'read_only': True},
        }

View看法

class BlogPostView(generics.ListCreateAPIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = blog_ser.BlogSerializer
    queryset = blog_model.BlogModel.objects.all()

    def perform_create(self, serializer):
        rand_num = random.randint(99, 222)
        blog_slug_str = f"{serializer.validated_data.get('blogtitle')}{rand_num}"
        sample_string_bytes = blog_slug_str.encode("ascii")
        base64_bytes = base64.b64encode(sample_string_bytes)
        slug = base64_bytes.decode("ascii")
        serializer.save(user=self.request.user, slug=slug)

React:反应:

Form JSX表单 JSX

                <form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={handleSubmit(onSubmit)}>
                    <div className="mb-4">
                        <label
                            className="block text-gray-700 text-sm font-bold mb-2"
                            htmlFor="title"
                        >
                            Title
                        </label>
                        <input
                            className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                            id="title"
                            type="text"
                            {...register('title', { required: true })}
                        />
                        {errors.title && <p className="text-red-500 text-xs italic">Title is required</p>}
                    </div>
                    <div className="mb-4">
                        <label
                            className="block text-gray-700 text-sm font-bold mb-2"
                            htmlFor="image"
                        >
                            Image
                        </label>
                        <input
                            className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                            id="image"
                            type="file"
                            {...register('image', { required: true })}
                        />
                        {errors.image && <p className="text-red-500 text-xs italic">Image is required</p>}
                    </div>
                    <div className="mb-4">
                        <label
                            className="block text-gray-700 text-sm font-bold mb-2"
                            htmlFor="details"
                        >
                            Details
                        </label>
                        <textarea
                            className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                            id="details"
                            {...register('details', { required: true })}
                        />
                        {errors.details && <p className="text-red-500 text-xs italic">Details is required</p>}

                    </div>
                    <button
                        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                        type="submit"
                    >
                        Submit
                    </button>
                </form>

Axios Call Axios 调用

const onSubmit = data => {
        console.log(data.image['0']);
        const payload = {
            blogtitle: data.title,
            blogcontent: data.details,
            blogimg: data.image,
        }
        console.log(payload);
        myAxios.post('/api/post/', payload).then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err.response.data);
        })
    }

When I am submitting the form the error is saying, The submitted data was not a file. Check the encoding type on the form.当我提交表单时,错误是, The submitted data was not a file. Check the encoding type on the form. The submitted data was not a file. Check the encoding type on the form. . .

When consoling the payload, I am getting:安慰有效载荷时,我得到:

{
    "blogtitle": "nok",
    "blogcontent": "asasa",
    "blogimg": {
        "0": {}
    }
}

Please Help Me...请帮我...

I have found the solution.我找到了解决方案。

Turns out I have to add a header 'Content-Type': 'multipart/form-data' to the Axios Request.原来我必须在 Axios 请求中添加一个标题'Content-Type': 'multipart/form-data'

I am posting the updated code below:我在下面发布更新的代码:

Axios Call Axios 调用

const onSubmit = data => {
        const payload = {
            blogtitle: data.title,
            blogcontent: data.details,
            blogimg: data.image['0'],
        }
        console.log(payload);
        myAxios.post('/api/post/', payload, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => {
            console.log(res);
        }).catch(err => {
            console.log(err.response.data);
        })
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 axios 将图像数组上传到 cloudinary 并使用 next.js 反应挂钩形式 - how to upload an array of images to cloudinary using axios and react hook form using next js 如何使用 React.js + Django Rest 框架保存带有表单提交的 blob 文件 - How Can I save a blob file with a form submission using React.js + Django Rest Framework 如何使用 Axios 将 CSRF Coo​​kie 从 React 发送到 Django Rest Framework - How to send CSRF Cookie from React to Django Rest Framework with Axios 如何使用 react 和 axios 将 GET 请求 header 中的数据发送到 Django rest 框架? - how to send data in GET request header using react and axios to Django rest framework? Django rest React 框架 401 错误 Axios - Django rest framework 401 error with React Axios Django Rest Framework 和 React Js(Axios API 请求):在不正确的身份验证尝试后,api 返回 400 - Django Rest Framework & React Js ( Axios API Request ): After Incorrect authentication attempt, api returns 400 无法使用React JS将文件上传到Django Rest框架 - cannot upload files to django rest framework using react js 使用 Axios 将文件从反应上传到 API CXF 2.5 java - Upload file from react using Axios to API CXF 2.5 java 无法使用反应挂钩表单获取文件上传的formData值 - Unable to get the formData values of file upload using react hook form 如何使用 react 和 django rest 框架将图像上传到 aws s3 - How to upload image to aws s3 using react and django rest framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM