[英]form validation fail in django with enctype=“multipart/form-data”
[英]How to upload a file from Angular 2 to Django Server? (enctype=“multipart/form-data”)
我已經在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)。 在此答案之后 ,這是我當前的實現:
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錯誤的請求錯誤消息(無法解析請求正文),並且我認為它發生在這一行:
f = request.FILES['myfile']
由於request.FILES需要enctype =“ multipart / form-data”,所以我的第一個直覺是我沒有正確傳遞multipart / form-data。
許多較早的討論都建議使用XMLHttpRequest,因為當時顯然不支持使用http上傳文件。 我也嘗試過,但仍然遇到相同的錯誤。
任何建議,將不勝感激。
我認為您的問題是:
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身份驗證時才需要auth。 如果不是,則要刪除以下行:
let bearer = 'Bearer ' + localStorage.getItem('currentUser');
xhr.setRequestHeader('Authorization', bearer);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.