繁体   English   中英

Angular 上传文件失败

[英]Angular failed to upload file

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

$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 时它不起作用

在此处输入图片说明

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

  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 进行测试的示例

在此处输入图片说明

为什么我有错误? 好像我的文件没有发送到后端,它的返回空值。 任何人都可以帮助我吗? 谢谢

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

formData.append('filename', file, file.name);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM