How to upload File from Angular 7 to Django - get error 403 (Forbidden)











up vote
0
down vote

favorite












I tried now in so many different ways, I can not get a file uploaded with Angular 7 to the Django Backend - shouldn't be so difficult?!



My .html:



<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>


uploader.component.ts



  fileToUpload: File = null;

handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
this.uploadFileToActivity();
}

uploadFileToActivity() {
this.uploaderService.post(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}


my uploader.service.ts that also shows the upload progress



public post( fileToUpload: File): Observable<number>{
const url = '/api/upload/';

var subject = new Subject<number>()
const req = new HttpRequest('POST', url, fileToUpload, {
reportProgress: true,
});

this.httpClient.request(req).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
const percentDone = Math.round(100 * event.loaded / event.total);
subject.next(percentDone);
} else if (event instanceof HttpResponse) {
subject.complete();
}
});
return subject.asObservable();
}


And in the Django backend:



views.py:



def post(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
#handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})


forms.py:



class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()


and urls.py:



urlpatterns = [
path(r'api/upload/', views.post, name='post'),
]


When I ran this I get



zone.js:2969 POST http://127.0.0.1:8000/api/upload/ 403 (Forbidden)


Do I need to include an authorization token? If yes: how?



Thanks a lot!



EDIT: After the useful input from Martin Urbanec I inspected the file upload request in the Browser. Here the result:



inspection of upload request from angular to django in browser



Someone any idea what I need to change in my code above to make this work?










share|improve this question




























    up vote
    0
    down vote

    favorite












    I tried now in so many different ways, I can not get a file uploaded with Angular 7 to the Django Backend - shouldn't be so difficult?!



    My .html:



    <div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
    id="file"
    (change)="handleFileInput($event.target.files)">
    </div>


    uploader.component.ts



      fileToUpload: File = null;

    handleFileInput(files: FileList) {
    this.fileToUpload = files.item(0);
    this.uploadFileToActivity();
    }

    uploadFileToActivity() {
    this.uploaderService.post(this.fileToUpload).subscribe(data => {
    // do something, if upload success
    }, error => {
    console.log(error);
    });
    }


    my uploader.service.ts that also shows the upload progress



    public post( fileToUpload: File): Observable<number>{
    const url = '/api/upload/';

    var subject = new Subject<number>()
    const req = new HttpRequest('POST', url, fileToUpload, {
    reportProgress: true,
    });

    this.httpClient.request(req).subscribe(event => {
    if (event.type === HttpEventType.UploadProgress) {
    const percentDone = Math.round(100 * event.loaded / event.total);
    subject.next(percentDone);
    } else if (event instanceof HttpResponse) {
    subject.complete();
    }
    });
    return subject.asObservable();
    }


    And in the Django backend:



    views.py:



    def post(request):
    if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
    #handle_uploaded_file(request.FILES['file'])
    return HttpResponseRedirect('/success/url/')
    else:
    form = UploadFileForm()
    return render(request, 'index.html', {'form': form})


    forms.py:



    class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()


    and urls.py:



    urlpatterns = [
    path(r'api/upload/', views.post, name='post'),
    ]


    When I ran this I get



    zone.js:2969 POST http://127.0.0.1:8000/api/upload/ 403 (Forbidden)


    Do I need to include an authorization token? If yes: how?



    Thanks a lot!



    EDIT: After the useful input from Martin Urbanec I inspected the file upload request in the Browser. Here the result:



    inspection of upload request from angular to django in browser



    Someone any idea what I need to change in my code above to make this work?










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I tried now in so many different ways, I can not get a file uploaded with Angular 7 to the Django Backend - shouldn't be so difficult?!



      My .html:



      <div class="form-group">
      <label for="file">Choose File</label>
      <input type="file"
      id="file"
      (change)="handleFileInput($event.target.files)">
      </div>


      uploader.component.ts



        fileToUpload: File = null;

      handleFileInput(files: FileList) {
      this.fileToUpload = files.item(0);
      this.uploadFileToActivity();
      }

      uploadFileToActivity() {
      this.uploaderService.post(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
      console.log(error);
      });
      }


      my uploader.service.ts that also shows the upload progress



      public post( fileToUpload: File): Observable<number>{
      const url = '/api/upload/';

      var subject = new Subject<number>()
      const req = new HttpRequest('POST', url, fileToUpload, {
      reportProgress: true,
      });

      this.httpClient.request(req).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress) {
      const percentDone = Math.round(100 * event.loaded / event.total);
      subject.next(percentDone);
      } else if (event instanceof HttpResponse) {
      subject.complete();
      }
      });
      return subject.asObservable();
      }


      And in the Django backend:



      views.py:



      def post(request):
      if request.method == 'POST':
      form = UploadFileForm(request.POST, request.FILES)
      if form.is_valid():
      #handle_uploaded_file(request.FILES['file'])
      return HttpResponseRedirect('/success/url/')
      else:
      form = UploadFileForm()
      return render(request, 'index.html', {'form': form})


      forms.py:



      class UploadFileForm(forms.Form):
      title = forms.CharField(max_length=50)
      file = forms.FileField()


      and urls.py:



      urlpatterns = [
      path(r'api/upload/', views.post, name='post'),
      ]


      When I ran this I get



      zone.js:2969 POST http://127.0.0.1:8000/api/upload/ 403 (Forbidden)


      Do I need to include an authorization token? If yes: how?



      Thanks a lot!



      EDIT: After the useful input from Martin Urbanec I inspected the file upload request in the Browser. Here the result:



      inspection of upload request from angular to django in browser



      Someone any idea what I need to change in my code above to make this work?










      share|improve this question















      I tried now in so many different ways, I can not get a file uploaded with Angular 7 to the Django Backend - shouldn't be so difficult?!



      My .html:



      <div class="form-group">
      <label for="file">Choose File</label>
      <input type="file"
      id="file"
      (change)="handleFileInput($event.target.files)">
      </div>


      uploader.component.ts



        fileToUpload: File = null;

      handleFileInput(files: FileList) {
      this.fileToUpload = files.item(0);
      this.uploadFileToActivity();
      }

      uploadFileToActivity() {
      this.uploaderService.post(this.fileToUpload).subscribe(data => {
      // do something, if upload success
      }, error => {
      console.log(error);
      });
      }


      my uploader.service.ts that also shows the upload progress



      public post( fileToUpload: File): Observable<number>{
      const url = '/api/upload/';

      var subject = new Subject<number>()
      const req = new HttpRequest('POST', url, fileToUpload, {
      reportProgress: true,
      });

      this.httpClient.request(req).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress) {
      const percentDone = Math.round(100 * event.loaded / event.total);
      subject.next(percentDone);
      } else if (event instanceof HttpResponse) {
      subject.complete();
      }
      });
      return subject.asObservable();
      }


      And in the Django backend:



      views.py:



      def post(request):
      if request.method == 'POST':
      form = UploadFileForm(request.POST, request.FILES)
      if form.is_valid():
      #handle_uploaded_file(request.FILES['file'])
      return HttpResponseRedirect('/success/url/')
      else:
      form = UploadFileForm()
      return render(request, 'index.html', {'form': form})


      forms.py:



      class UploadFileForm(forms.Form):
      title = forms.CharField(max_length=50)
      file = forms.FileField()


      and urls.py:



      urlpatterns = [
      path(r'api/upload/', views.post, name='post'),
      ]


      When I ran this I get



      zone.js:2969 POST http://127.0.0.1:8000/api/upload/ 403 (Forbidden)


      Do I need to include an authorization token? If yes: how?



      Thanks a lot!



      EDIT: After the useful input from Martin Urbanec I inspected the file upload request in the Browser. Here the result:



      inspection of upload request from angular to django in browser



      Someone any idea what I need to change in my code above to make this work?







      django angular file-upload http-post angular-httpclient






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 14:57

























      asked Nov 10 at 18:34









      smaica

      117315




      117315
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          Content-Type header must be multipart/form-data to transfer any files. I recommend you to check if this header is sent to your Django backend.






          share|improve this answer





















          • Thanks, I didn't set the content type, unfortunately this didnt solve my problem. Still I get error 403. How can I check if the header is correctly sent? Breakpoints in the backend are never reached.
            – smaica
            Nov 11 at 9:53










          • You can open developer console in your browser. For instance in Google Chrome it's F12. In this developer console, find Network tab, open it and try to upload a file. You can then open the request and examine it, including its headers.
            – Martin Urbanec
            Nov 11 at 13:02










          • Ah I see, thanks for this idea. Maybe you can help me figuring out what I need to change to make this work? I added my findings above in the question
            – smaica
            Nov 11 at 14:58











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53242175%2fhow-to-upload-file-from-angular-7-to-django-get-error-403-forbidden%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote













          Content-Type header must be multipart/form-data to transfer any files. I recommend you to check if this header is sent to your Django backend.






          share|improve this answer





















          • Thanks, I didn't set the content type, unfortunately this didnt solve my problem. Still I get error 403. How can I check if the header is correctly sent? Breakpoints in the backend are never reached.
            – smaica
            Nov 11 at 9:53










          • You can open developer console in your browser. For instance in Google Chrome it's F12. In this developer console, find Network tab, open it and try to upload a file. You can then open the request and examine it, including its headers.
            – Martin Urbanec
            Nov 11 at 13:02










          • Ah I see, thanks for this idea. Maybe you can help me figuring out what I need to change to make this work? I added my findings above in the question
            – smaica
            Nov 11 at 14:58















          up vote
          0
          down vote













          Content-Type header must be multipart/form-data to transfer any files. I recommend you to check if this header is sent to your Django backend.






          share|improve this answer





















          • Thanks, I didn't set the content type, unfortunately this didnt solve my problem. Still I get error 403. How can I check if the header is correctly sent? Breakpoints in the backend are never reached.
            – smaica
            Nov 11 at 9:53










          • You can open developer console in your browser. For instance in Google Chrome it's F12. In this developer console, find Network tab, open it and try to upload a file. You can then open the request and examine it, including its headers.
            – Martin Urbanec
            Nov 11 at 13:02










          • Ah I see, thanks for this idea. Maybe you can help me figuring out what I need to change to make this work? I added my findings above in the question
            – smaica
            Nov 11 at 14:58













          up vote
          0
          down vote










          up vote
          0
          down vote









          Content-Type header must be multipart/form-data to transfer any files. I recommend you to check if this header is sent to your Django backend.






          share|improve this answer












          Content-Type header must be multipart/form-data to transfer any files. I recommend you to check if this header is sent to your Django backend.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 23:26









          Martin Urbanec

          2818




          2818












          • Thanks, I didn't set the content type, unfortunately this didnt solve my problem. Still I get error 403. How can I check if the header is correctly sent? Breakpoints in the backend are never reached.
            – smaica
            Nov 11 at 9:53










          • You can open developer console in your browser. For instance in Google Chrome it's F12. In this developer console, find Network tab, open it and try to upload a file. You can then open the request and examine it, including its headers.
            – Martin Urbanec
            Nov 11 at 13:02










          • Ah I see, thanks for this idea. Maybe you can help me figuring out what I need to change to make this work? I added my findings above in the question
            – smaica
            Nov 11 at 14:58


















          • Thanks, I didn't set the content type, unfortunately this didnt solve my problem. Still I get error 403. How can I check if the header is correctly sent? Breakpoints in the backend are never reached.
            – smaica
            Nov 11 at 9:53










          • You can open developer console in your browser. For instance in Google Chrome it's F12. In this developer console, find Network tab, open it and try to upload a file. You can then open the request and examine it, including its headers.
            – Martin Urbanec
            Nov 11 at 13:02










          • Ah I see, thanks for this idea. Maybe you can help me figuring out what I need to change to make this work? I added my findings above in the question
            – smaica
            Nov 11 at 14:58
















          Thanks, I didn't set the content type, unfortunately this didnt solve my problem. Still I get error 403. How can I check if the header is correctly sent? Breakpoints in the backend are never reached.
          – smaica
          Nov 11 at 9:53




          Thanks, I didn't set the content type, unfortunately this didnt solve my problem. Still I get error 403. How can I check if the header is correctly sent? Breakpoints in the backend are never reached.
          – smaica
          Nov 11 at 9:53












          You can open developer console in your browser. For instance in Google Chrome it's F12. In this developer console, find Network tab, open it and try to upload a file. You can then open the request and examine it, including its headers.
          – Martin Urbanec
          Nov 11 at 13:02




          You can open developer console in your browser. For instance in Google Chrome it's F12. In this developer console, find Network tab, open it and try to upload a file. You can then open the request and examine it, including its headers.
          – Martin Urbanec
          Nov 11 at 13:02












          Ah I see, thanks for this idea. Maybe you can help me figuring out what I need to change to make this work? I added my findings above in the question
          – smaica
          Nov 11 at 14:58




          Ah I see, thanks for this idea. Maybe you can help me figuring out what I need to change to make this work? I added my findings above in the question
          – smaica
          Nov 11 at 14:58


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53242175%2fhow-to-upload-file-from-angular-7-to-django-get-error-403-forbidden%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues