繁体   English   中英

将图像从 Angular 上传到 Laravel

[英]Uploading Image From Angular to Laravel

我试图将图像从我的 Angular 应用程序上传到 Laravel。 我的问题是它无法完成。 我的代码有问题吗? 我也必须使用其他输入字段提交它。 请在下面检查我的代码。

HTML

 <form [formGroup]="servicesForm" (ngSubmit)="onCreateService(servicesForm)">
    <div class="col-sm-8"> 
        <input  type="file" accept=".png, .jpg, .jpeg" (change)="onSelectImage($event)" class="form-control" formControlName="icon">
    </div> 
     <button type="submit" >Save</button>
</form>

TS

  onSelectImage(event) {
     this.selectedImage = new FormData();
     this.selectedImage.append('avatar', event.srcElement.files[0], event.srcElement.files[0].name);
     console.log(this.selectedImage);
  }

  onCreateService(form: FormGroup) {
    const formData = {
      image: this.selectedImage,
      name: this.servicesForm.get('name').value,
      amount: this.servicesForm.get('price').value,
      description: this.servicesForm.get('content').value
    };
    console.log(formData);
  }

在此处输入图片说明

您需要像下面一样更改ts代码,您需要将整个数据作为formdata发送,而不仅仅是图像

  onSelectImage(event) {
     this.selectedImage = event.srcElement.files[0];
  }

  onCreateService(form: FormGroup) {
    const formData = new FormData();
    formData.append('image', this.selectedImage, this.selectedImage.name);
    formData.append('name', this.servicesForm.get('name').value);
    formData.append('amount', this.servicesForm.get('price').value);
    formData.append('description', this.servicesForm.get('content').value);
    console.log(formData);
  }

您尝试使用此编码。 这张图片 Uploding 代码使用前端 Angular 来后端 Laravel-8。

下面是 Angular ts 文件编码。 saveOrUpdate包含文件保存编码和更新编码

import { Component,  OnInit } from '@angular/core';
import { FormBuilder} from '@angular/forms';
import { Product } from '../../models/product.model';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment';

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

    file: any;
    imagePath: any;
    currentSupplierId: number;

    constructor(
        private formBuilder: FormBuilder,
        private http: HttpClient,
        ) { }

    ngOnInit() {
        this.imagePath = environment.baseUrl + "/public/img/products/";
    }

    onFileChanged(event) {
        console.log(event);
        this.file = event.target.files[0];

        const reader = new FileReader();
        reader.onload = e => {
            return this.imageSrc = reader.result;
        };

        reader.readAsDataURL(this.file);
    }

    saveOrUpdate(product: Product) {
                    debugger;
                    const myFormData = new FormData();
                    const headers = new HttpHeaders();
                    headers.append('Content-Type', 'multipart/form-data');
                    headers.append('Accept', 'application/json');
                    myFormData.append('image', this.file);
                    myFormData.append('code', product.code);
                    this.http.post(environment.utilityApiBasePath + 'upload', myFormData, {
                        headers: headers
                    }).subscribe(data => {
                        console.log(data);
                    });
                   
                } else {
                    const myFormData = new FormData();
                    const headers = new HttpHeaders();
                    headers.append('Content-Type', 'multipart/form-data');
                    headers.append('Accept', 'application/json');
                    myFormData.append('image', this.file);
                    myFormData.append('code', product.code);
                    this.http.delete(environment.utilityApiBasePath + 'deleteImage/' + product.code + '.jpg').subscribe(
                        data1 => {
                            console.log(data1);
                            this.http.post(environment.utilityApiBasePath + 'upload', myFormData, {
                                headers: headers
                            }).subscribe(data => {
                                console.log(data);
                            });
                        });
    }

这是 Larwell 控制器文件编码。

$file->move(public_path('supplier'), $picture);

我们需要在上面的代码供应商中并行创建路径。 在这个路径中应该是我们在Larwell 文件的public 文件夹中创建的。

  public function uploadProfilePhoto(Request $request) {
        if ($request->hasFile('image'))
        {
            $file      = $request->file('image');
            $filename  = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            // $picture   = date('His').'-'.$filename;
            $picture =  $request['code'].'.jpg';
            $file->move(public_path('/supplier'), $picture);
            return response()->json(["message" => "Image Uploaded Succesfully"]);
        }
        else
        {
            return response()->json(["message" => "Select image first."]);
        }

    }

这将在我更新时删除文件夹中的旧图像并重新兑现新图像。 所以下面是删除代码的图像

  public function deleteImage($image){
        $filename = public_path().'/supplier/'.$image;
        \File::delete($filename);
        return response()->json(['message'=> 'Successfully Deleted' ]);
    }  

索引.html

<body ng-controller="myCtrl">
<div class="file-upload">
    <input type="text" ng-model="name">
    <input type="file" file-model="myFile"/>
    <button ng-click="uploadFile()">upload me</button>
</div>

应用程序.js

var myApp = angular.module('myApp', []);

myApp.directive('fileModel', ['$parse', function ($parse) {
    return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
   };
}]);

// We can write our own fileUpload service to reuse it in the controller
myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl, name){
         var fd = new FormData();
         fd.append('file', file);
         fd.append('name', name);
         $http.post(uploadUrl, fd, {
             transformRequest: angular.identity,
             headers: {'Content-Type': undefined,'Process-Data': false}
         })
         .success(function(){
            console.log("Success");
         })
         .error(function(){
            console.log("Success");
         });
     }
 }]);

 myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

   $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' );
        console.dir(file);

        var uploadUrl = "save_form.php";
        var text = $scope.name;
        fileUpload.uploadFileToUrl(file, uploadUrl, text);
   };

}]);

save_form.php

<?php

     $target_dir = "./upload/";
     $name = $_POST['name'];
     print_r($_FILES);
     $target_file = $target_dir . basename($_FILES["file"]["name"]);

     move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);

     //write code for saving to database 
     include_once "config.php";

     // Create connection
     $conn = new mysqli($servername, $username, $password, $dbname);
     // Check connection
     if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
     }

     $sql = "INSERT INTO MyData (name,filename) VALUES ('".$name."','".basename($_FILES["file"]["name"])."')";

     if ($conn->query($sql) === TRUE) {
         echo json_encode($_FILES["file"]); // new file uploaded
     } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
     }

     $conn->close();

?>

暂无
暂无

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

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