1

I am using Django Rest Framework and Angular 2 to upload a file. My files looks like this. What do I do wrong? Tell me please. Thank you very much.

Django file:

view

class ProjectTaskViewSets(viewsets.ModelViewSet):
    queryset = ProjectTask.objects.all()
    serializer_class = ProjectTaskSerializers
    parser_classes = (MultiPartParser, FormParser,)

    def perform_create(self, serializer, format=None):
        file = self.request.data.get('file', False)
        if file:
            serializer.save(
                text=serializer.validated_data.get('text'),
                project=serializer.validated_data.get('project'),
                file=file)
        else:
            serializer.save(
                text=serializer.validated_data.get('text'),
                project=serializer.validated_data.get('project')
            )

    def filter_queryset(self, queryset):
        project = self.request.query_params.get('project', False)
        if project:
            queryset = queryset.filter(project_id=project)
        return queryset

serializers

class ProjectTaskSerializers(serializers.ModelSerializer):

    class Meta:
        model = ProjectTask
        fields = '__all__'

    def create(self, validated_data):
        return ProjectTask.objects.create(**validated_data)

model

class ProjectTask(models.Model):
    text = models.CharField(_('text'), max_length=200, blank=True, null=True)
    file = models.FileField(
        _('file'), blank=True, null=True, upload_to=directory_path
    )
    project = models.ForeignKey(
        DashboardProject,
        verbose_name=_('project'),
        related_name='task_list',
        on_delete=models.CASCADE
    )

    class Meta:
        verbose_name = _('project task')
        verbose_name_plural = _('project tasks')
        ordering = ('-id',)

    def __str__(self):
        return self.text[:20]

    def __repr__(self):
        return '<ProjectTask {}>'.format(self.text[:20])

Angular files

component

saveTask() {
    this.taskForm.value.file = this.file;
    console.log(this.taskForm.value);
    this.taskService.addTask(this.file).subscribe(
      (data) => {
        console.log(data)
      },
      (error) => {
        console.log(error)
      }
    );
  }

  onChange(event) {
    let files = event.target.files;
    console.log(files);
    let formData: FormData = new FormData();
    formData.append('file', files[0], files[0].name);
    //if (files.length > 0) {
    //  let formData: FormData = new FormData();
    //  for (let file of files) {
    //    formData.append('files', file, file.name);
    //  }
    console.log(formData);
    this.file = formData
  }

service

  addTask(model:any): Observable<TaskId> {

      let headers = new Headers();
      headers.set('Accept', 'application/json');
      // headers.set('Authorization', 'JWT ' + localStorage.getItem('id_token'));
      // headers.set('Content-Type', 'multipart/form-data' );
      // headers.set('Content-Type', 'application/json' );
      headers.set('Content-Type', '*/*' );
      let options = new RequestOptions({ headers: headers });
      return this.http.post(URL, model, options).map((response: Response) => response.json());

  }

input

<input type="file" id="file" name="file" formControlName="file" (change)="onChange($event)">
3
  • Do you encounter any errors? If yes, please post them! Commented Feb 26, 2017 at 20:06
  • Object { _body: "{"detail":"Multipart form parse error - Invalid boundary in multipart: None", status: 400, ok: false, statusText: "Bad Request", headers: Object, type: 2, url: "127.0.0.1:8000/api/task" } Commented Feb 26, 2017 at 20:10
  • Possible duplicate of MultiPartParserError :- Invalid boundary Commented Feb 26, 2017 at 20:13

1 Answer 1

1

I use it like this: angular2-service(set the content type you need: here):

  uploadFile(file, filename: string){
let headers = new Headers({ 'Content-Type': 'application/vnd.ms-excel'});
headers.append("X-CSRFToken", this.utils.getCookie('csrftoken'));
headers.append("Content-Disposition", "attachment; filename=" + filename);

let options = new RequestOptions({ headers: headers });
return this.http.put(this.connectorsUrl + 'manage-files/', file , options)
                .map(res => res.json())
                .catch(this.handleError);

}

In django view:

    def put(self, request, format=None):

    file_obj = request.FILES['file']

    self.logger.info('Uploading file')
    uploaded = bicloudreposervice.upload_file(request.user.username, file_obj)

    return out

If you want to use TempFiles handler add to settings:

FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler',

]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.