python - 如何将带有 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;
}
解决方案
我看不出你想如何发送数据,但如果你想用 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,我认为最好将这种东西放在后端以防止被操纵的请求。我认为最好将复杂的东西以及与后端相关的任何服务器数据放在一起。只是我的观点。
推荐阅读
- function - 在 Kotlin 中使用异常作为默认参数
- firebase - Firebase 具有不同的函数环境变量
- java - 使用 Micronaut 为 MongoDB 注册编解码器
- ios - iOS -> 应用内购买的非消费品是否真的包含代码?
- python-3.x - Python从不同文件中的类导入
- android - 如何通过正确的 Crashlytics 错误分组获得更好的 RxJava 堆栈跟踪
- android - 将统一更新到最新版本 2019.2 后,我的游戏中添加了一些权限
- multilingual - Neos CMS:避免多语言设置中的重复内容节点
- ruby-on-rails - NoMethodError(JsonWebToken:Module 的未定义方法“编码”)
- php - 未定义属性:Illuminate\Database\Eloquent\Builder::$total