如何使用 DRF 和 React 上传文件?

How to upload files with DRF and React?

我正在学习 Django Rest Framework,一切都很顺利,直到我不得不创建一个服务来将文件上传到我的 application.As,虽然我阅读了文档,但我无法理解它。 首先我想澄清一下,我不是编程专家,我是 新手,但我每天都在这里学习更多。 到目前为止,我已经设法理解: 文件和照片不存储在数据库中。这些文件存储在一个文件夹中。

这是正确的吗?

我有一个允许我上传多个文件的表格 示例:

file.txt、document.doc、photo.png等...

我的观点(前端):

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

const Form = () => {
  const [state_files, setState_Files] = useState(null);

  const UploadFiles = function (event) {
    setState_Files(event);
  };

  const InsertFiles = async function () {
    const formData = new FormData();
    for (let index = 0; index < state_files.length; index++) {
      formData.append("files", state_files[index]);
    }

    await axios
      .post("http://127.0.0.1:8000/api/v1/upload/", formData)
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };
  return (
    <>
      <input
        type="file"
        name="files"
        multiple
        onChange={() => InsertFiles(event.target.files)}
      />
      <button>Upload All files</button>
    </>
  );
};

export default Form;

后端

url.py

path("upload/", Storage_View.as_view(), name="storage-index"),

storage/view.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser


class Storage_View(APIView):
    parser_classes = [MultiPartParser]

    def put(self, request, filename, format=None):
        file_obj = request.data['file']
        # ...
        # What do I have to do here?
        # ...
        return Response({'received data': request.data})

问题:

  1. 为什么我没有看到使用 DFR 工具上传文件的按钮?见附件

  1. 文档没有解释我在函数注释中必须做什么 https://www.django-rest-framework.org/api-guide/parsers/ def put(...):

  2. 如何指定存储上传文件的路径?

求指导。

1: show your models for more detail. you have to use filefield or imagefield in your model. You can google and read more about these fields.

2: put is for update, write your post method to save data. You don't have to really do anything serious there. just check if serializer.is_Valid() for request.data and if valid do serializer.save(). the file or image will be uploaded to upload_to folder which you define in your model and you will get the link.

3: read more about upload_to in Django. you can define this with the model field.

我使用了 ModelViewSet,这是创建方法的样子 -

def create(self, request, format=None):
    data = request.data
    if isinstance(data, list):  # <- is the main logic
        serializer = self.get_serializer(data=request.data, many=True)
    else:
        serializer = self.get_serializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

您正在从前端传递一个列表,默认情况下,Django 使用字典,因此您必须管理它。将此视为您开始编写代码并编写 post 方法。

如有疑问,请随时写更多,希望对您有所帮助:)