【问题标题】:How can I upload a file with JSON data to django rest api?如何将带有 JSON 数据的文件上传到 django rest api?
【发布时间】:2021-02-08 08:28:36
【问题描述】:

我使用 Angular 作为前端范围,使用 Django Rest 作为后端。现在我面临一个想要创建模型的情况。模型的结构本质上非常复杂,我可以使用其他一些简单的方法,但使用 JSON 并传递文件可以真正简化逻辑并让流程变得非常高效。

我已经尝试了很多,但似乎没有一种方法有效。

有人可以用标准方式帮助我,或者告诉我是否可能。

这是我要上传的 Typescript 的结构。

import { v4 as uuid4 } from 'uuid';

export interface CompleteReport{
  title: string;
  description: string;
  author: string;
  article_upload_images: Array<uuid4>,
  presentation_upload_images: Array<uuid4>,
  report_article: ReportArticle,
  report_image: ReportImage,
  report_podcast: ReportPodcast,
  report_presentation: ReportPresentation,
  report_video: ReportVideo,
}

export interface ReportArticle{
  file: File;
  body: string;
}

export interface ReportPodcast{
  file: any;
}

export interface ReportVideo{
  file: Array<File>;
}

export interface ReportImage{
  file: File;
  body: string;
}

export interface ReportPresentation{
  body: string;
}

export interface UploadImage{
  file: File;
}

【问题讨论】:

    标签: python django angular typescript django-rest-framework


    【解决方案1】:

    我不明白你想如何发送数据,但如果你想用 multipart/data-form 发送数据,我认为你应该对你的报告结构做一些小改动。

    JSON 不支持二进制。所以,你不能把文件放在上面。您需要拆分文件并报告 JSON。

    (async () => {
      let formData = new FormData();
      // here's how to send file on multipart/data-form via fetch
      let reportFile = document.querySelector('#file');
      formData.append("file", imagefile.files[0]);
      // here's your report json
      let report = {
        ...
      };
      formData.append("report", JSON.stringify(report));
      
      // send request and upload
      let response = await fetch(url, {
        method: 'POST',
        body: formData
      });
    
      // do something with response
      let responseText = await response.text();
      console.log(responseText)
    })();
    

    我在您的前端代码上看到了 UUID,我认为最好将这种东西放在后端以防止被操纵的请求。我认为最好将复杂的东西以及与后端相关的任何服务器数据放在一起。只是我的看法。

    【讨论】:

      猜你喜欢
      • 2018-06-08
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      相关资源
      最近更新 更多