javascript - Angular 8 使用 FormControl 将文件上传到 Django 服务器
问题描述
注意:我不想使用 FormData,如果可能的话想使用 FormControl。
我有一个向 Django 服务器发送一些数据的表单,它处理并存储数据。
这是我的 Django 函数
def create(self, request):
company = CompanyForm(request.data, request.FILES)
if company.is_valid():
company = company.save()
serializer = CompanySerializer(company)
return JsonResponse(request.data, safe=False)
else:
return JsonResponse(request.errors, safe=False)
这是角形式
<form [formGroup]="companyForm" id="ngForm" enctype="multipart/form-data"
#documentEditForm="ngForm" (ngSubmit)="CreateCompany()">
//Some other fields.
<mat-form-field>
<ngx-mat-file-input formControlName="com_logo" placeholder="Logo"></ngx-mat-file-input>
<mat-icon matSuffix>folder</mat-icon>
</mat-form-field>
</form>
如您所见,我使用ngx-mat-file-input
输入文件处理
这是 FormControl 的组件代码
companyForm = new FormGroup({
com_name: new FormControl('', Validators.required),
com_owner: new FormControl('', Validators.required),
com_phone: new FormControl('', Validators.required),
com_address: new FormControl(),
com_email: new FormControl(),
com_status: new FormControl(),
com_website: new FormControl(),
com_logo: new FormControl(),
});
// From Array of errors to show on front end.
formErrors: any = {}
CreateCompany(): void {
this.apiService.createItem(this.companyForm.value, 'company').subscribe(
result => {},
error => {}
);
}
当我检查控制台时,我将图像信息发送到服务器,但是当我返回request.FILES
Django 时它是空的。
{com_name: "Pomtech", com_owner: "JSsss", com_phone: "072044920", com_address: "9170 N. Beacon Rd",…}
com_name: "Pomtech"
com_owner: "JSsss"
com_phone: "072044920"
com_address: "9170 N. Beacon Rd"
com_email: "n.karimi@gmail.com"
com_status: null
com_website: null
com_logo: {_files: [{}], delimiter: ", ", _fileNames: "employer-13.png"}
_files: [{}]
delimiter: ", "
_fileNames: "employer-13.png"
如果有帮助,我也使用 DjangoResetFramework。
那么将文件数据发送到 Django 并存储有什么问题呢?
解决方案
后端可能使用的是 simpleJSON parser
而不是Multipart parser
. 检查您的 Django 设置以查看您使用的解析器。
from rest_framework.decorators import api_view
from rest_framework.decorators import parser_classes
from rest_framework.parsers import MultiPartParser
@api_view(['POST'])
@parser_classes([MultiPartParser])
def example_view(request, format=None):
# request.data has both files and other parsed data
return Response({'received data and files': request.data})
有关更多信息,请参阅Django rest 框架解析器
推荐阅读
- javascript - react es6 项目无法在 Safari 和 Internet Explorer 上运行
- html - 为什么我的导航栏组件在 Angular 中不起作用?
- javascript - 通过 JavaScript 将样式顶部添加到其他高度元素的 ID 元素
- django - 对产品进行分类
- java - 如何修复Firefox浏览器中的ajax调用,但在chrome浏览器中工作正常
- json - 使用 JQ 在树状 json 对象中沿每条路径收集所有根到叶值
- javascript - 有没有办法在创建侦听器时记录索引的值,以便在调用侦听器函数时使用相同的值?
- here-api - 获取路径链接的形状
- java - 为什么我的堆栈代码中的 pop 方法不执行?
- java - 如何在 Java 中获取 @param 文本?