【问题标题】:Fetch and display image in reactjs from django backend using json使用json从django后端获取并显示reactjs中的图像
【发布时间】:2020-12-12 00:52:51
【问题描述】:

在 model.py 文件的 imageField 中默认使用图像。

from django.db import models
class Product(models.Model):
  item_title= models.CharField(max_length=50)
  item_desc=models.TextField()
  item_price=models.IntegerField()
  item_image=models.ImageField(upload_to='post_images',default='default.png')

这是我的序列化程序类

from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
  class Meta:
    model = Product
    fields= ('item_title', 'item_desc', 'item_price', 'item_image')

views.py 是-

class ProductView(viewsets.ModelViewSet):
  serializer_class = ProductSerializer
  queryset = Product.objects.all()

在localhost:8000收到的json数据是 localhost:8000/api/products

在 App.js 的前端(react js)获取数据。这是代码

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      productList: [],
    };
  }

  refreshList = () => {
    axios
     .get("/api/protducts/")
     .then((res) => this.setState({ productList: res.data }))
     .catch((err) => console.log(err));
  };
  componentWillMount() {
    this.refreshList();
  }

  render() {
    return (
      <div>
        {this.state.productList.map((item) => (
          <Product key={item.id} item={item} />
        ))}
      </div>
    );
  }
 }
 export default App;

前端的Product组件是

class Product extends Component {
  constructor(props) {
    super(props);
  }
  render() {
  return (
    <div class="jumbotron col-sm-2">
      <img src={this.props.item.item_image}></img>
      <mark>{this.props.item.item_title}</mark>
      <div class="lead">{this.props.item.item_desc}</div>
      <div class="text-primary">{this.props.item.item_price}</div>
    </div>
  );}}
  export default Product;

前端显示的数据不显示任何图像。 localhost:3000

【问题讨论】:

  • 你使用过自定义的 axios 实例吗?如果不是,那么您的get 请求将被定向到localhost:3000/api/products/
  • 获取请求能够定向到 localhost:3000/api/products/。
  • 并且数据能够从后端显示在前端。请参考问题中按赞给出的图像。我只能显示图像。字符串数据正常工作。

标签: json django reactjs django-rest-framework react-fullstack


【解决方案1】:

您不能使用 JSON 传递图像。您需要将其转换为 base64 或任何编码。让我给你解释一个简单的方法:

  1. 在您的模型中创建一个名为 item_image_url 的字段。
class Product(models.Model):
  item_title= models.CharField(max_length=50)
  item_desc=models.TextField()
  item_price=models.IntegerField()
  item_image=models.ImageField(upload_to='post_images',default='default.png')
  item_image_url = models.TextField()
  1. 覆盖Product 类中的默认保存方法,并将您的图像在线托管到任何图像托管网站,如imgbb 或aws。下面给出了一个示例代码。
def save(self):
        encodedString = base64.b64encode(self.item_image.file.read())
        data = {"key": os.environ.get("IMG_BB"), "image": encodedString.decode("utf-8")}
        uploadedImageInfo = requests.post("https://api.imgbb.com/1/upload", data=data)
        jsonResponse = json.loads(uploadedImageInfo.text)
        self.item_image_url = jsonResponse["data"]["display_url"]
        super().save()
  1. 现在,在您的序列化程序类中,添加 id 字段以在 react 中正确呈现,并添加一个字段 item_image_url,其中将包含 imgbb 上托管的图像的 URL。
class ProductSerializer(serializers.ModelSerializer):
  class Meta:
    model = Product
    fields= ('id', 'item_title', 'item_desc', 'item_price', 'item_image_url')

希望这会有所帮助。如果您需要任何进一步的说明,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2021-07-04
    • 2021-12-03
    • 2014-03-19
    • 1970-01-01
    相关资源
    最近更新 更多