首页 > 解决方案 > 如何在 react 中使用 graphene-django 和 axios 将图像上传到我的服务器?

问题描述

任何人都可以共享突变代码以及graphene-django模型以创建图像上传突变以及如何在反应中使用Axios上传图像?

我不想使用 Apollo,因为我的整个项目都使用 graphene-django 和 Axios 运行,我面临的唯一问题是图像上传。

这是我的代码:

#models.py
class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, 
               blank=True, null=True)
    status = models.BooleanField(default=True)
    product_name = models.CharField(max_length=300, blank=True, null=True)
    price = models.BigIntegerField(blank=True, null=True)
    tax_slab = models.IntegerField(
        max_length=100, default=0, choices=SLAB, null=True, blank=True)
    description = models.TextField(max_length=500, blank=True, null=True)
    image = models.FileField(null=True, blank=True)


#mutations.py
from graphene_django.forms.mutation import DjangoModelFormMutation

class ProductMutation(DjangoModelFormMutation):
    class Meta:
        form_class = ProductForm

class Mutation(graphene.AbstractType):
    create_product = ProductMutation.Field()

标签: reactjsgraphqlaxiosgraphene-pythongraphene-django

解决方案


请看代码:Image upload with axios, graphene-django and django-graphql-jwt

https://medium.com/@amiya_rbehera/image-upload-with-axios-graphene-django-and-django-graphql-jwt-53e1e2cab0e7

import React, { Component } from 'react';
import axios from 'axios'
import { graphql } from "../config.json"



class ProfileUpload extends Component {
    state = { 
        data: { imageFile:"" }
     }

     handleImageChange = ({ currentTarget: input}) => {
        const data = { ...this.state.data};
        data[input.name] = input.files[0];
        console.log(input.name)
        console.log(input.files[0])
        this.setState({ data });
       
      }

      handleImageUpload = async () => {
          const data = new FormData();
          data.append('imageFile', this.state.data.imageFile)
          const query = `mutation{
            createProfileImage {
              profileImage{
                id
                user {
                  id
                  email
                }
                image                
              }              
            }
          }`
          data.append('query', query)
            for (var pair of data.entries()) {
                console.log(pair[0]+ ', ' + pair[1]); 
            }
         let result ="";
          await axios({
              method: 'post',
              url: graphql,
              data: data,
              config: { headers: {'Content-Tranfer-Encoding': 'multipart/form-data', 'Content-Type': 'application/graphql'}},
              withCredentials: true,
          })
          .then(function(response){
              console.log(response);
              result = response;
          })
          .catch(function(response){
              console.log(response)
              result = response;
          })

          return result;

      }

      handleSubmit = async (event) => {
          event.preventDefault();
          const uploadres = await this.handleImageUpload()
          console.log(uploadres.data, 'uploadres')

      }
    render() { 
       
        return ( 
            <React.Fragment>
                <form onSubmit={event => this.handleSubmit(event)}>
                    <div className="form-group">
                        <label htmlFor="ImageFile">Profile Image</label>
                        <input name="imageFile" id="image" required type="file" className="form-control"  onChange={this.handleImageChange}/>
                    </div>
                    <button type="submit" className="btn btn-primary">Submit</button>
                </form>
            </React.Fragment>
         );
    }
}
 
export default ProfileUpload;


推荐阅读