django - 从角度提交时 /media/C:/fakepath/example.png 的 SuspiciousFileOperation
问题描述
我正在构建一个 Angular + Django 项目,用户可以在其中将文件上传到模型:
模型:
def upload_path(instance, filename):
return '/'.join(['files', str(instance.titulo), filename])
class File(models.Model):
titulo = models.CharField(max_length=154, null=False, blank=False)
file = models.FileField(upload_to=upload_path, null=False)
当我通过 Insomnia 发送发布请求时,一切正常,文件保存在媒体根(媒体)中,但是当我通过 Angular 发送时,它保存的路径与标题相似,并且发生错误。
角度:
<div class="row">
<label style="margin-left: 10px;">Anexos</label>
<label id="label-input">
<input [(ngModel)]="ticket.file" type="file" single id="input-file">
</label>
</div>
服务:
htttpHeaders = new HttpHeaders().set("Content-Type", "application/json").set('Authorization', this.token);
public saveNewTicket(ticket): Observable<any> {
return this.http.post(this.baseUrl + "ticket/", ticket, {
headers: this.htttpHeaders
});
}
解决方案
问题是我将数据作为 json 发送,并且发送文件或图像需要在 multipart/form-data 中,如下所示:
HTML:
<form>
<label id="thumbnail">
<input type="file" class="file_selector" (change)=(onFileSelected($event)) />
</label>
<button class="btn btn-success" (click)="onUpload()" style="float: right;">Salvar Anexo</button>
</form>
TS:创建了一个常量文件
onFileSelected(e) {
this.file = e.target.files[0];
}
onUpload() {
this.crudService.updateFile(this.business.id, this.file).subscribe(data => {
console.log(data);
}, err => {
console.error(err);
});
}
crudService.ts:创建函数并实例化一个新的表单数据,而不仅仅是附加数据
public updateFile(ticketid, file): Observable<any> {
const body = new FormData();
body.append('id', ticketid);
body.append('files', file, file.name);
return this.http.put(this.baseUrl + 'ticket/' + ticketid + '/', body, {
headers: this.htttpHeadersFormData
});
}
推荐阅读
- java - 如何使用 wsl 2 运行或构建 java 程序
- python - 如何在 ajax 函数中呈现 Django render() 响应?
- linux - 问题while循环比较文件中的当前日期和日期
- python - Pytube3,如何选择要下载的流的ŕesoulution
- c - 不兼容的指针类型,预期为浮点 * 但参数的类型为浮点 (*)[2]
- javascript - 这行代码在javascript中意味着什么?
- python - 无法使用 Selenium Python 将鼠标悬停在元素上
- c++ - 如何在类中重载 operator+ 以在 C++ 中添加两个数组?
- reactjs - 试图让两个函数在一次 onclick 中运行
- python - Music21 和 MuseScore 无法在 jupyter notebook 中显示 .png