首页 > 解决方案 > 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 并存储有什么问题呢?

标签: javascriptpythondjangoangulardjango-rest-framework

解决方案


后端可能使用的是 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 框架解析器


推荐阅读