Angular无法上传文件

问题描述 投票:1回答:1

这是我用来上传文件的一堆后端代码。

$app->post('/upload/{studentid}', function(Request $request, Response $response, $args) {

    $uploadedFiles = $request->getUploadedFiles();

    // handle single input with single file upload
    $uploadedFile = $uploadedFiles['filename'];
    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {

        $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);

        // ubah nama file dengan id buku
        $filename = sprintf('%s.%0.8s', $args["studentid"], $extension);

        $directory = $this->get('settings')['upload_directory'];
        $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);

        // simpan nama file ke database
        $sql = "UPDATE feepaid SET filename=:filename WHERE studentid=:studentid";
        $stmt = $this->db->prepare($sql);
        $params = [
            ":studentid" => $args["studentid"],
            ":filename" => $filename
        ];

        if($stmt->execute($params)){
            // ambil base url dan gabungkan dengan file name untuk membentuk URL file
            $url = $request->getUri()->getBaseUrl()."/Upload/".$filename;
            return $response->withJson(["status" => "success", "data" => $url], 200);
        } else {
            return $response->withJson(["status" => "failed", "data" => "0"], 200);
        } 
    }
});

当我使用邮差测试它的工作,但我对Angular很新。当我在我的Angular应用程序中实现api时它不起作用

enter image description here

这是我用来从角度应用程序上传文件的代码

  fileChange(event) {
    const fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      const file: File = fileList[0];
      const formData: FormData = new FormData();
      formData.append('uploadFile', file, file.name);
      const headers = new Headers();
      /** In Angular 5, including the header Content-Type can invalidate your request */
      // headers.append('Content-Type', 'multipart/form-data');
      // headers.append('Accept', 'application/json');
      const id = sessionStorage.getItem('userId');
      // const options = new RequestOptions({ headers: headers });
      this.http.post('http://localhost:8080' + '/upload/' + id , formData)
        .subscribe(
          data => console.log('success'),
          error => console.log(error)
        );
    }

  }

这是我使用Postman测试的例子

enter image description here

为什么我有错误?好像我的文件没有发送到后端并返回null值。有人可以帮帮我吗?谢谢

angular typescript angular7
1个回答
1
投票

当您将密钥检索为filename时,您需要为表单数据发送确切的键值对,因此请尝试更改:

formData.append('filename', file, file.name);
© www.soinside.com 2019 - 2024. All rights reserved.