首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >上传Angular 8中的图片到PHP服务

上传Angular 8中的图片到PHP服务
EN

Stack Overflow用户
提问于 2019-11-23 02:14:49
回答 2查看 1.4K关注 0票数 0

我的代码是Angular 8

代码语言:javascript
复制
<form [formGroup]="upload" (ngSubmit)="sendParameters()">
            <div class="input-image">
                <p>
                    <input id="upload-image" formControlName="image" type="file" name="file" accept="image/*" (change)="onFileChanged($event.target.files)">
                </p>
            </div>
            <div class="input-active">
                <p>
                    <mat-slide-toggle class="example-margin" color="primary" (change)="onChange($event)"> STATUS</mat-slide-toggle>
                </p>
            </div>

            <div class="button">
                <p>
                    <button mat-raised-button>UPLOAD</button>
                </p>
            </div>
        </form>
代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ConnectionsService } from '../../connections.service';
import { AuthenticationService } from '../../authentication.service';
import { LocationStrategy } from '@angular/common';
import { User } from '../../Model/user';
import { Subscription } from 'rxjs';
import { ToastrService } from 'ngx-toastr';

class ImageSnippet {
  constructor(public src: string, public file: File) {}
}

@Component({
  selector: 'app-subir-imagen',
  templateUrl: './subir-imagen.component.html',
  styleUrls: ['./subir-imagen.component.css']
})
export class SubirImagenComponent implements OnInit {

  public currentUser: User;
  public currentUserSubscription: Subscription;
  public users: User[] = [];

  public upload;
  public selectedFile: File = null;
  public status: number;
  public idEmpleado: number;
  public loading = false;

  constructor(
    public formBuilder: FormBuilder,
    public locationStrategy: LocationStrategy,
    public authenticationService: AuthenticationService,
    public service: ConnectionsService,
    public toastr: ToastrService) {
      this.currentUserSubscription = this.authenticationService.currentUser.subscribe(user => {
        this.currentUser = user;
      });
    }

  ngOnInit() {
    this.idEmpleado = this.currentUser.id || this.currentUser[0].id;
    this.upload = this.formBuilder.group({
      image: ['', Validators.required]
    });
  }

  onFileChanged(files: FileList) {
    this.selectedFile = files.item(0);
  }

  onChange(event) {
    if (event.checked === true) {
      this.status = 1;
    } else if (event.checked === false) {
      this.status = 2;
    }
  }

  sendParameters() {
    this.service.setImage(
      this.selectedFile,
      this.status,
      this.idEmpleado
    ).subscribe(
      res => {
        console.log(res);
        this.toastr.error('Success', '', {progressAnimation: 'decreasing', timeOut: 3000});
      },
      error => {
        console.log(error);
        this.toastr.error('Error', '', {progressAnimation: 'decreasing', timeOut: 3000});
      }
    );
  }
}

我的服务

代码语言:javascript
复制
setImage(image: any, status: number, idEmpleado: number): Observable<any> {
    const formData: FormData = new FormData();
    formData.append('fileKey', image.file);
    return this.http
      .post(environment.apiUrl + 'image/upload.php', formData, 
      {
        headers: new HttpHeaders()
          .set('Content-Type', 'multipart/form-data')
      }
    );
  }

这是接收信息并进行保存过程的PHP服务

代码语言:javascript
复制
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: multipart/form-data; charset=UTF-8");
header("Access-Control-Allow-Methods: PUT, GET, POST, FILES");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$folder ="./uploads/";
$image = $_FILES['image']['name'];
$path = $folder . $image;
$target_file=$folder.basename($_FILES["image"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
$allowed=array('jpeg','png' ,'jpg');


$ext=pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {

    http_response_code(503);
    echo json_encode(array("message" => "Sorry, only JPG, JPEG, PNG & GIF  files are allowed."));

}

else{ 

    move_uploaded_file( $_FILES['image']['tmp_name'], $path); 
}

但是我看不到错误在我的代码中的哪里,因为我没有收到图像,如果我用postman做测试,它允许我发送图像并保存它,但不能用Angular,除非我没有正确发送它

EN

回答 2

Stack Overflow用户

发布于 2020-07-22 06:40:55

您需要删除formData中的.file,对我而言,我必须删除服务中的标头才能使其正常工作

最终结果:

代码语言:javascript
复制
setImage(image: File, status: number, idEmpleado: number): Observable<any> {
    const formData: FormData = new FormData();
    formData.append('image', image);
    return this.http
      .post(environment.apiUrl + 'image/upload.php', formData
    );
}
票数 1
EN

Stack Overflow用户

发布于 2019-11-23 02:30:19

您正在将文件追加为formData.append('fileKey', image.file)

因此,在PHP代码中访问文件时,它应该是:

代码语言:javascript
复制
$image = $_FILES['fileKey']['name'];

或者只更改您的angular代码,而不更改PHP代码

代码语言:javascript
复制
formData.append('image', image.file)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58999693

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档