首页 > 解决方案 > 如何将带有 JSON 数据的文件上传到 django rest api?

问题描述

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

我一直在尝试很多,但似乎没有一种方法有效。

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

这是我要上传的打字稿的结构。

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;
}

标签: pythondjangoangulartypescriptdjango-rest-framework

解决方案


我看不出你想如何发送数据,但如果你想用 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,我认为最好将这种东西放在后端以防止被操纵的请求。我认为最好将复杂的东西以及与后端相关的任何服务器数据放在一起。只是我的观点。


推荐阅读