【问题标题】:How to upload image with Angular and PHP如何使用 Angular 和 PHP 上传图片
【发布时间】:2020-07-30 16:04:58
【问题描述】:

我是 Angular 的新手,我正在尝试从 Angular 上传图片但出现 4 个错误:

1) 在 post 方法中:找不到名称“formData”。您是说“FormData”吗?ts(2552)
2)在订阅方法中: const headers: HttpHeaders
没有重载匹配此调用。
重载 1 个,共 5 个,
3)在订阅方法中:找不到名称“文件”。您是说“文件”吗?ts(2552)
4)在this.url中:输入'string | ArrayBuffer' 不可分配给类型
'string'。
类型 'ArrayBuffer' 不能分配给类型 'string'

下面我附上代码。

public imagePath;
  constructor(private http: HttpClient) { }
  url: string;
  ngOnInit() {
  }
  onSelectFile(event) 
  { // called each time file input changes
    if (event.target.files && event.target.files[0]) 
    {
        var reader = new FileReader();
        this.imagePath = event.target.files;

        for (const file of this.imagePath) 
        {
          const formData = new FormData();
          formData.append('image', file, file.name);
        }
        const headers = new HttpHeaders();
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');

        this.http.post('http://localhost/imageupload.php', formData).subscribe( headers, console.log(file.name) );

        reader.readAsDataURL(event.target.files[0]); // read file as data url

        reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;

      }
    }
  }

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    常量是块作用域的,你没有外部作用域的访问常量(因为是块作用域)

    public imagePath;
      constructor(private http: HttpClient) { }
      url: string;
      ngOnInit() {
      }
      onSelectFile(event) 
      { // called each time file input changes
        if (event.target.files && event.target.files[0]) 
        {
            var reader = new FileReader();
            this.imagePath = event.target.files;
    
            for (const file of this.imagePath) 
            {
              const formData = new FormData();
              formData.append('image', file, file.name);
    
              const headers = new HttpHeaders();
              headers.append('Content-Type', 'multipart/form-data');
              headers.append('Accept', 'application/json');
    
              this.http.post('http://localhost/imageupload.php', formData, { headers }).subscribe(response => console.log(response));
    
              reader.readAsDataURL(event.target.files[0]); // read file as data url
    
              reader.onload = (event) => { // called once readAsDataURL is completed
              this.url = event.target.result;
            }
          }
        }
      }
    

    【讨论】:

    • 但在 headers 和 this.url 上的 subscribe 方法仍然出错
    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2015-05-18
    相关资源
    最近更新 更多