Angular 5 - 将图像上传到资产文件夹 - 编辑:在服务器托管中的图像文件夹中

时间:2018-03-23 04:51:51

标签: angular

在资源文件夹中上传图片时遇到问题。我试图直接访问资产文件夹,但它说错误404。

karyawan.component.html:

<form class="example-form">
  <input type="file" (change)="onFileSelected($event)">
  <div class="button-row">
    <button mat-raised-button color="primary" (click)="onUpload()">Register</button>
</div>
</form>

karyawan.component.ts

 import { Component, OnInit } from '@angular/core';
    import {FormControl, FormGroupDirective, NgForm, Validators} from '@angular/forms';
    import {ErrorStateMatcher} from '@angular/material/core';

    import { HttpClient } from '@angular/common/http';
    import { Http, Headers, RequestOptions } from '@angular/http';

    @Component({
      selector: 'app-karyawan',
      templateUrl: './karyawan.component.html',
      styleUrls: ['./karyawan.component.css']
    })
    export class KaryawanComponent implements OnInit {
      selectedFile : File = null;

      constructor(private http: HttpClient) { }

      ngOnInit() {
      }


      onFileSelected(event){
        this.selectedFile = <File> event.target.files[0];
      }

      onUpload(){
        const fd = new FormData();
        fd.append('image', this.selectedFile, this.selectedFile.name);
        this.http.post('http://localhost:4200/assets', fd)
          .subscribe(res => {
            console.log(res);
          });

      }

    }

编辑:karyawan.component.ts

onUpload(){
    const fd = new FormData();
    // const request = new XMLHttpRequest();
    fd.append('image', this.selectedFile, this.selectedFile.name);
    // request.open("POST","http://edugamescenter.com/uploadimage.php");
    // request.send(fd);
    // http://localhost:4200/assets/image
    this.http.post('http://edugamescenter.com/uploadimage.php', fd)
      .subscribe(res => {
        console.log(res);
      });

我在服务器上创建了一个PHP文件: uploadimage.php

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}

$image_tmp = $_FILES['image']['tmp_name'];
$image_name = $_FILES['image']['name'];

$gambar = move_uploaded_file($image_tmp, 'http://edugamescenter.com/image/'.$image_name);

echo 'Here is some more debugging info:';
print_r($_FILES);

?>

响应:

Server Response

状态代码:200 OK
但是,图像未上传到文件夹图像中 有什么建议??

0 个答案:

没有答案