【问题标题】:Uploading Image From Angular to Laravel将图像从 Angular 上传到 Laravel
【发布时间】:2019-02-14 11:00:34
【问题描述】:

我尝试将图像从我的 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);
  }

【问题讨论】:

  • 您遇到了什么问题?
  • @Javascript 爱好者 - SKT。服务器说图片:[“图片必须是类型的文件:jpg,jpeg]
  • 我已经发布了一个答案,请检查一次。您需要将整个数据作为 formdata 发送,而不仅仅是图像

标签: angular angular6 angular-reactive-forms angular-forms angular4-forms


【解决方案1】:

您尝试使用此编码。此图片上传代码使用前端 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);
                            });
                        });
    }

这是拉威尔控制器文件编码。

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

我们需要在 supplier 上面的代码中创建平行路径。在这个路径中应该是我们在公用文件夹中创建的Larwell文件。

  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' ]);
    }  

【讨论】:

    【解决方案2】:

    index.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>
    

    app.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();
    
    ?>
    

    【讨论】:

    • 我没有使用 AngularJS
    【解决方案3】:

    您需要更改您的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);
      }
    

    【讨论】:

    • 错误不是现在的图像。错误是金额:[“金额字段是必需的。”]描述:[“描述字段是必需的。”]名称:[“名称字段是必需的。”]
    • @Joseph 您如何在服务器端访问文件?使用$_FILES 数组?
    • 是的。我就这样访问它
    • @Joseph 然后代替 ts 文件中的 formdata,您可以将此请求的标头设置为 Content-Type: multipart/form-data,并且您必须发送 C:\fakepath\xyz.jpeg
    • @Joseph 我可以在 45 分钟后帮助你,我要去办公室了。同时,如果您得到最佳答案,那很好。
    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2018-07-17
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    相关资源
    最近更新 更多