简体   繁体   中英

How to upload a file from Angular 2 to Django Server? (enctype=“multipart/form-data”)

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.

I think your problem is:

enctype="multipart/form-data"

If you're using a form service sometimes the HTML form tags cause problems. I would try it just using:

<input type="file" name="myfile" required>
    <button type="submit">Upload</button>

I would definitely still use some type of form, just thought this would be quick to debug why it is failing. I would use the angular 2 form library.

Also, here is a multipart upload service that I use:

import { Injectable } from '@angular/core';


@Injectable()
export class UploadService {

    public makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {            
            let formData: any = new FormData();
            let xhr = new XMLHttpRequest();
            for(let i =0; i < files.length; i++) {
                formData.append('file', files[i], files[i].name);
            }
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(xhr.response);                        
                    } else {
                        reject(xhr.response);
                    }
                }
            };
            let bearer = 'Bearer ' + localStorage.getItem('currentUser');               
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Authorization', bearer);
            xhr.send(formData);
        });
    }
}

you only need the auth if you're using JWT authentication. If you are not, you want to take out these lines:

let bearer = 'Bearer ' + localStorage.getItem('currentUser'); 
xhr.setRequestHeader('Authorization', bearer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM