如何在react中使用graphene-django和axios将图像上传到服务器?

时间:2019-05-17 09:51:22

标签: reactjs graphql axios graphene-python graphene-django

任何人都可以共享用于突变的代码以及用于石墨烯-django的模型来创建用于图像上传的突变吗?如何在React中使用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()

1 个答案:

答案 0 :(得分:0)

请查看代码: 使用axios,graphene-django和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;