I have seen multiple questions on stackoverflow similar to this but I have not been able to solve the following issue.
I can successfully upload a file using this html form:
<form method="POST" action="//127.0.0.1:8000/upload" enctype="multipart/form-data">
<input type="file" name="myfile" required>
<button type="submit">Upload</button>
</form>
and here is how the file is handled on the server side:
views.py
def upload_file(request):
f = request.FILES['myfile']
with open('media/name.jpg', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return HttpResponse('Done')
Everything works perfectly up to this point. The file gets uploaded and saved as name.jpg on disk. Now, I would like to replace the html above to post the file without a url redirect (using angular 2 http). Following this answer, here is my current implementation:
file-upload.component.ts
import { Component, ElementRef } from '@angular/core';
import {Http, Headers, RequestOptions, Response} from '@angular/http';
@Component({
selector: 'file-upload',
template: '<input type="file" name="myfile">'
})
export class FileUploadComponent {
constructor(private http: Http, private el: ElementRef) {}
upload() {
var headers = new Headers();
headers.append('Content-Type','multipart/form-data');
let inputEl = this.el.nativeElement.firstElementChild;
if (inputEl.files.length > 0) {
let file:FileList = inputEl.files[0];
this.http
.post('http://127.0.0.1:8000/upload', file, {headers: headers})
.subscribe();
}
}
and call it like this:
<file-upload #myfile (change)="myfile.upload()"></file-upload>
I get a 400 bad request error saying (Unable to parse request body), and I think it happens at this line:
f = request.FILES['myfile']
since request.FILES requires enctype="multipart/form-data", my first hunch is that I am not passing multipart/form-data correctly.
A lot of older discussions suggest the use of XMLHttpRequest since at the time upload file with http was not supported apparently. I tried that as well and still get the same error.
Any suggestions would be appreciated.