csv Django API拒绝文件

fkaflof6  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(156)

我尝试发送一个csv文件到我的Django API并使用进程数据响应,但是当我发送它时,我得到了错误:
django.utils.datastructures.MultiValueDictKeyError: "文件"
这是我的React代码:

import { useState } from 'react';
import './App.css';

function App() {

  const [file, setFile] = useState(null);

  const uploadFiles = e =>{
    setFile(e);
  }

  const insertFile = async() => {
    const f = new FormData();
    f.append("file", file);

    await fetch(
      'http://localhost:8000/api/',
      {
        method: 'POST',
        headers: { 'content-type': 'multipart/form-data' },
        body: f,
      })
      .then((response) => response.json())
      .then((data)=>{
        console.log(data);
      })
      .catch(error=>{
        console.log(error);
      });

  }

  return (
    <>
      <input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files)}/>
      <button onClick={()=>insertFile()}>Insertar</button>
    </>
  );
}

export default App;

And this is my view.py file that will process the information, for now, I just want to get the csv info in the frontend side, so the logic of how to process data doesn't matter right now.

@api_view(['POST'])
def eda(request):
    file = request.FILES['file']
    data = []
    with open(file, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        for rows in csvReader: 
            data.append(rows)
    
    response = {
        'csvData': data 
    }

    return Response(response)
oxalkeyp

oxalkeyp1#

看起来你的文件根本没有添加到FormData中。这是因为你发送的是一个文件列表,而不是一个文件。因此,

<input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files)}/>

用这个

<input type="file" name="file" onChange={(e)=>uploadFiles(e.target.files[0])}/>

在Django这边使用这个:

file = request.FILES.get('file') # won't raise exception
if file is None:
    # show some error response

相关问题