首页 > 解决方案 > 从角度提交时 /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
    });
  }

标签: djangoangularfileupload

解决方案


问题是我将数据作为 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
    });
  }

推荐阅读