我现在已经尝试了许多不同的方式,我无法将Angular 7上载的文件上传到Django后端-应该没有那么难吗?!
我的 .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);
});
}
我的 uploader.service.ts 还显示了上传进度
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();
}
在Django后端中:
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()
和 urls.py:
urlpatterns = [
path(r'api/upload/', views.post, name='post'),
]
当我运行它时,我得到
zone.js:2969 POST http://127.0.0.1:8000/api/upload/ 403 (Forbidden)
我需要包括授权令牌吗?如果是,怎么办?
非常感谢!
编辑:在Martin Urbanec提供了有用的输入之后,我检查了浏览器中的文件上传请求。结果如下:
有人知道我需要在上面的代码中进行哪些更改才能使它工作?
答案 0 :(得分:0)
Content-Type
标头必须为multipart/form-data
才能传输任何文件。我建议您检查此标头是否发送到Django后端。