【问题标题】:Angular failed to upload fileAngular 上传文件失败
【发布时间】:2019-04-10 23:01:45
【问题描述】:

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

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

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

【问题讨论】:

  • 该 API 是来自 PostMan 还是 fiddler?
  • 它在 PostMan 上工作。我没有在提琴手上测试它
  • 你能告诉我们你是如何在邮递员上发送数据的吗(截图)?
  • 我已经编辑了我的问题
  • 试试:formData.append('filename', file);

标签: angular typescript angular7


【解决方案1】:

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

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

【讨论】:

  • 是的,已经这样做了,但它没有将文件名插入数据库。知道为什么吗?
  • 如果邮递员可以这样做,那么问题出在角度代码本身
  • 我试过 console.log(data) 但它返回 null ,是的必须是角度代码。还是谢谢你:)
  • 你能把代码从subscribe改成Promise吗?
  • 我使用过 FormData 但我的后端是 Web.API
猜你喜欢
  • 2013-06-09
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 2020-06-12
相关资源
最近更新 更多