Strapi+React+Axios实现图片上传的示例代码

类似内容

使用React作为前端上传图片到Strapi的实现过程

一 安装Axios实现http请求

yarn add axios
or
npm install axios --save

注意:Strapi的媒体库地址是:http:localhost:1337/upload,也就是文件POST请求地址

二 构建表单

import { useState } from 'react';
import axios from 'axios';

function App() {

  const [files,setFiles] = useState()

  const uploadImage = async () => {
      //posting logic will go here
  }

  return (
      <form onSubmit={uploadImage}>
        <input 
            type="file"
            onChange={(e)=>setFiles(e.target.files)}
        />
        <input type="submit" value="Submit" />
      </form>
  );
}

三 上传文件

const uploadImage = async (e) => {
    e.preventDefault();

    const formData = new FormData()

    formData.append('files', files[0])

    axios.post("http://localhost:1337/upload", formData)
    .then((response)=>{
        //after success
    }).catch((error)=>{
        //handle error
    })
}

四 关联Content-Type中的字段

const uploadImage = async (e) => {
    e.preventDefault();

    const formData = new FormData()

    formData.append('files', files[0])

    axios.post("http://localhost:1337/upload", formData)
    .then((response)=>{

      const imageId = response.data[0].id

      axios.post("http://localhost:1337/people",{image:imageId}).then((response)=>{
        //handle success
      }).catch((error)=>{
          //handle error
        })
    }).catch((error)=>{
        //handle error
    })

}

Post Comment