Angular File Upload

后端 未结 12 2141
名媛妹妹
名媛妹妹 2020-11-22 10:04

I\'m a beginner with Angular, I want to know how to create Angular 5 File upload part, I\'m trying to find any tutorial or doc, but I don\'t see anything a

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 10:53

    Here is how I did it to upload the excel files:
    Directory structure:

    app
    |-----uploadcomponent
               |-----uploadcomponent.module.ts
               |-----uploadcomponent.html
    |-----app.module.ts
    |-----app.component.ts
    |-----app.service.ts
    

    uploadcomponent.html

    uploadcomponent.ts

        import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
        import { Component, OnInit } from '@angular/core';
        ....
        export class UploadComponent implements OnInit {
            form: FormGroup;
            constructor(private formBuilder: FormBuilder, private uploadService: AppService) {}
            ngOnInit() {  
                this.form = this.formBuilder.group({
                   profile: ['']
                });
            }
    
            onChange(event) {
                if (event.target.files.length > 0) {
                  const file = event.target.files[0];
    
                  this.form.get('profile').setValue(file);
                  console.log(this.form.get('profile').value)
                }
            }
    
            onSubmit() {
               const formData = new FormData();
               formData.append('file', this.form.get('profile').value);
    
               this.uploadService.upload(formData).subscribe(
                 (res) => {
                   this.response = res;
    
                   console.log(res);
    
                 },
                 (err) => {  
                   console.log(err);
                 });
             }
        }
    

    app.service.ts

        upload(formData) {
            const endpoint = this.service_url+'upload/';
            const httpOptions = headers: new HttpHeaders({    <<<< Changes are here
                'Authorization': 'token xxxxxxx'})
            };
            return this.http.post(endpoint, formData, httpOptions);
        }
    

    In Backend I use DJango REST Framework.
    models.py

    from __future__ import unicode_literals
    from django.db import models
    from django.db import connection
    from django_mysql.models import JSONField, Model
    import uuid
    import os
    
    
    def change_filename(instance, filename):
        extension = filename.split('.')[-1]
        file_name = os.path.splitext(filename)[0]
        uuid_name = uuid.uuid4()
        return file_name+"_"+str(uuid_name)+"."+extension
    
    class UploadTemplate (Model):
        id = models.AutoField(primary_key=True)
        file = models.FileField(blank=False, null=False, upload_to=change_filename)
    
        def __str__(self):
            return str(self.file.name)
    

    views.py.

    class UploadView(APIView):
        serializer_class = UploadSerializer
        parser_classes = [MultiPartParser]       
    
        def get_queryset(self):
            queryset = UploadTemplate.objects.all()
            return queryset
    
        def post(self, request, *args, **kwargs):
            file_serializer = UploadSerializer(data=request.data)
            status = None
            message = None
            if file_serializer.is_valid():
                file_serializer.save()
                status = "Success"
                message = "Success"
            else:
                status = "Failure"
                message = "Failure!"
            content = {'status': status, 'message': message}
            return Response(content)
    

    serializers.py.

    from uploadtemplate.models import UploadTemplate
    from rest_framework import serializers
    
    class UploadSerializer(serializers.ModelSerializer):
        class Meta:
            model = UploadTemplate
            fields = '__all__'   
    

    urls.py.

    router.register(r'uploadtemplate', uploadtemplateviews.UploadTemplateView, 
        base_name='UploadTemplate')
    urlpatterns = [
        ....
        url(r'upload/', uploadtemplateviews.UploadTemplateView.as_view()),
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    
    if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    MEDIA_URL and MEDIA_ROOT is defined in settings.py of the project.

    Thanks!

提交回复
热议问题