【问题标题】:How to upload a file from Angular 2 to Django Server? (enctype="multipart/form-data")如何将文件从 Angular 2 上传到 Django 服务器? (enctype="multipart/form-data")
【发布时间】:2017-04-04 03:02:33
【问题描述】:

我在 stackoverflow 上看到了多个与此类似的问题,但我无法解决以下问题。

我可以使用这个 html 表单成功上传文件:

<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>

这是在服务器端处理文件的方式:

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')

到目前为止,一切都完美无缺。该文件被上传并保存为 name.jpg 在磁盘上。现在,我想替换上面的 html 来发布没有 url 重定向的文件(使用 angular 2 http)。在this answer 之后,这是我当前的实现:

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();
    }
}

然后这样称呼它:

<file-upload #myfile (change)="myfile.upload()"></file-upload>

我收到 400 bad request 错误消息(无法解析请求正文),我认为它发生在这一行:

f = request.FILES['myfile']

由于 request.FILES 需要 enctype="multipart/form-data",我的第一个预感是我没有正确传递 multipart/form-data。

许多较早的讨论建议使用 XMLHttpRequest,因为当时显然不支持使用 http 上传文件。我也试过了,还是一样的错误。

任何建议将不胜感激。

【问题讨论】:

    标签: django angular asyncfileupload angular2-http


    【解决方案1】:

    我认为你的问题是:

    enctype="multipart/form-data"
    

    如果您使用表单服务,HTML 表单标签有时会导致问题。我会尝试使用:

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

    我肯定还是会使用某种类型的表单,只是认为这样可以快速调试它失败的原因。我会使用 angular 2 表单库。

    另外,这是我使用的分段上传服务:

    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);
            });
        }
    }
    

    只有在使用 JWT 身份验证时才需要身份验证。如果你不是,你想去掉这些行:

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

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2013-11-26
      • 1970-01-01
      • 2014-02-20
      相关资源
      最近更新 更多