【发布时间】:2021-12-01 11:46:54
【问题描述】:
我有一个基本的 django 应用程序,它只需将 excel 文件上传到 oracle 数据库。我创建了一个 python 类(上传器)来对文件进行一些完整性检查并上传到数据库。
我已经成功地在 Django 模板中使用 HTML 创建了一个 UI,效果很好。
但是,我想将前端迁移到 Angular 前端。
我已经创建了 Angular 应用程序,但我目前正在努力了解如何将前端连接到 django。 在线研究后,他们建议使用模型、序列化程序,但因为我通过独立的 python 类进行上传,我不知道如何使用这种方法连接两者。我假设我必须使用 HttpClient 以某种方式连接到这个视图?
任何帮助将不胜感激。谢谢
上传/views.py
def clickToUpload(request):
if request.method == 'POST':
if 'form' in request.POST:
try:
upload_instance = uploader(request.FILES['file'], request.POST['date'])
_ = upload_instance.run_process('File', update_log=True)
upload_message= "Success"
except Exception as e:
upload_message = 'Error: ' + str(e)
return render(request, 'Upload/upload.html', {'upload_message':upload_message})
更新 视图.py
from rest_framework.response import Response
from rest_framework import status
def clickToUpload(request):
if request.method == 'POST':
if 'form' in request.POST:
try:
upload_instance = uploader(request.FILES['file'], request.POST['date'])
_ = upload_instance.run_process('File', update_log=True)
upload_message= "Success"
return Response(upload_message, status=status.HTTP_201_CREATED)
except Exception as e:
upload_message = 'Error: ' + str(e)
return Response(upload_message , status=status.HTTP_400_BAD_REQUEST)
file-upload.service.ts
export class FileUploadService {
DJANGO_SERVER: string = "http://127.0.0.1:8000";
constructor(private http:HttpClient) { }
public upload(data: any) {
return this.http.post<any>(`${this.DJANGO_SERVER}/lcr-upload/upload/`, data);
}
}
上传.component.ts
constructor(private fileUploadService: FileUploadService) { }
ngOnInit(): void {
}
onChange(event: any) {
this.file = event.target.files[0];
console.log("This file is: " + this.file)
}
onUpload() {
this.loading = !this.loading;
console.log(this.file);
this.fileUploadService.upload(this.file).subscribe(
(event: any) => {
if (typeof (event) === 'object') {
this.shortLink = event.link;
this.loading = false;
console.log("OnUploadClicked")
}
}
)
}
}
upload.component.html
<div class="input-group">
<input class="form-control" type="file" (change)="onChange($event)">
<!-- <span><button (click)="onUpload()" class="btn btn-dark">Upload</button></span> -->
</div>
<br>
<div class="input-group" style="font-size: 18px">
<mat-form-field appearance="outline">
<mat-label>Choose a Date</mat-label>
<input matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<div class="input-group" style="font-size: 18px">
<button class="btn btn-success" (click)="onUpload()">Upload</button>
</div>
【问题讨论】: