无法将照片从Angular 8上传到Laravel:“在null上调用成员函数extension()”错误

问题描述 投票:0回答:1

在我的应用程序中:Angular 8字体结尾和Laravel 5.8后端。我需要上传照片。我正在关注本教程:ACADE MIND

我的模板代码

 <input  *ngIf="photoEdit" enctype="multipart/form-data" type="file" (change)="onFileChanged($event)" #fileInput>
 <button *ngIf="photoEdit" class="btn btn-xs btn-danger" (click)="onUpload()"> Save</button>
 <button class="btn btn-small btn-primary" (click)="editPhoto()">Change Photo</button>

在以下方法中:

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

显示控制台日志中已选择文件。

onUpload()方法:

onUpload() {
    // this.http is the injected HttpClient
    const uploadData = new FormData();
    uploadData.append('photo', this.selectedFile,this.selectedFile.name);
    // this.http.post('http://127.0.0.1:8000/api/photo/upload', { 'photo' : this.selectedFile }, this.authService.getHeader())
    //   .subscribe(event => {
    //     console.log(event);
    //   });
    this.http.post('http://127.0.0.1:8000/api/photo/upload', uploadData, this.authService.getHeader())
      .subscribe(event => {
        console.log(event);
      });
  }

getHeader()

public getHeader() {
    var token: string;
    token = "bearer" + this.getToken();
    let headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': token
    });
    let options = { headers: headers };
    return options;
  }

我正在:

   error : "Call to a member function extension() on null"

从邮递员上传的照片工作正常。在服务器中,我已经打印了整个请求。以下是服务器日志:

[Tue Nov 26 07:34:27 2019] Log In
[Tue Nov 26 07:34:34 2019] POST /api/photo/upload HTTP/1.1
Accept:          application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,bn;q=0.8
Authorization:   bearereyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTU3NDczMjA2NywiZXhwIjoxNTc0NzM1NjY3LCJuYmYiOjE1NzQ3MzIwNjcsImp0aSI6IlhCQVR4YnlpVG
t5dzlha3IiLCJzdWIiOjQsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.Ul7eztDS024iN2AMgzwsHUiu4R4gcQctqtHnGftYaNw
Connection:      keep-alive
Content-Length:  39015
Content-Type:    application/json
Host:            127.0.0.1:8000
Origin:          http://localhost:4200
Referer:         http://localhost:4200/profile
Sec-Fetch-Mode:  cors
Sec-Fetch-Site:  cross-site
User-Agent:      Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36

------WebKitFormBoundaryvkYLBOFceCLCopiW
Content-Disposition: form-data; name="photo"; filename="3_4_5.png"
Content-Type: image/png

服务器端功能:

    public function upload(request $request)
        {
            error_log($request);
            $extension = $request->file('photo')->extension();

            if ($request->hasFile('photo')) {
                error_log("FILE");
            }
            $fileName = "logedUserName";
            $fileName =  $fileName . "." . $extension;
            $savedPhotoName = $request->photo->storeAs('public', $fileName);
            return $savedPhotoName;
        }
angular typescript laravel-5 file-upload
1个回答
0
投票

尝试将您的Laravel函数设置为在像这样的空上传中实际上返回错误;

public function upload(request $request)
{
    // Do we have a file?
    if ($request->hasFile("photo")) {
        error_log("Error::: No file provided in upload");
        return "error_no_file";
    }
    else
    {
        // TODO: Validate the file is what you want (size, mime type, etc.)

        $file = $request->file("photo");
        $filename = "loggedUserName-" . "." . $file->getClientOriginalExtension();

        // save to storage/app/photos
        $path = $file->storeAs("photos", $filename);

        // Return the path
        return $path;
    }
}

然后作为最佳猜测,尝试在您的getHeader()中删除“ Content-Type”标头或将其显式设置为“ multipart / form-data”而不是“ application / json”

© www.soinside.com 2019 - 2024. All rights reserved.