reactjs - 如何在 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()
解决方案
请看代码:Image upload with axios, graphene-django and django-graphql-jwt
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;
推荐阅读
- javascript - 出现错误未捕获的 ReferenceError:未定义 firebase
- python - 使用 asyncio 触发并忘记发布请求
- gridview - Liferay网格结构,制作等宽行
- python - 使用 Google 进行 Raspberry Pi 语音识别有错误
- haskell - 列出任一列表
- javascript - 使用 json 数据在 Reat Native 中使用 FlatList 的自定义网格视图?
- excel - 带有变量 VBA 的 IF AND 公式
- flutter - 我该如何解决这个颤振安装错误
- python - 将文本除以 2 个字符
- mongodb - MongoDB 返回所有文档(即使它们是双重的)