简体   繁体   中英

File upload from Angular 9 to Laravel not working

I am trying to upload image from angular 9 to Laravel . I configured angular project in my local machine. And Laravel project is in another server. I am using api calls to get data from larvel to angular. All are working fine but File upload is not working. The request get in server is null.(in usercontroller) Below is my code:

Angular

product.component.html [file upload form]

<form [formGroup]="mediaFormGroup" (ngSubmit)="uploadMedia()">
<label>Image:</label>
<input  type="file" name="media_file" (change)="onFileChange($event)" />
<button type="submit" [disabled]="mediaStatus">Upload</button> 
</form>

product.component.ts [file change function and upload function]

onFileChange(event) {
if (event.target.files.length > 0) {
this.file = event.target.files[0];
this.thumbFileName = <File>event.target.files[0].name;
var reader = new FileReader();  
reader.onload = (event: any) => {  
      this.thumbUrl = event.target.result;  
}  
reader.readAsDataURL(this.file);  
}
}

uploadMedia(){
const formData = new FormData();
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
formData.append('thumbimage', this.file);
this.http.post(`${this.API_URL}/user/uploadImage`, formData, {
      headers: headers
      }).subscribe(data => {
          return data;
      });
}

Laravel

routes/api.php

Route::post('user/uploadImage', "User\UserController@uploadImage");

UserController.php

public static function uploadImage(Request $request){
       //return $request;  // null
 if ($request->hasFile('thumbimage'))
 {
       $file      = $request->file('thumbimage');
       $filename  = $file->getClientOriginalName();
       $extension = $file->getClientOriginalExtension();
       $picture   = date('His').'-'.$filename;
       $file->move(public_path('tImg'), $picture);
       return response()->json(["message" => "Image Uploaded Succesfully"]);
  }else{
       return response()->json(["message" => "Select image first."]); // returns this
  }
}

The uploadImage function return Select image first

The request is getting as null in server.

What is wrong in my code? I think someone can help me..

I also had this problem. I ended up using the PHP files array.

$_FILES['filename']['tmp_name']

import this class:

use Illuminate\Http\UploadedFile;

then create a new UploadedFile;

$name = $_FILES['filename']['name'];
$tempPath = $_FILES['filename']['tmp_name']
$file = new UploadedFile(
    $tempPath,
    $name,
);

// do other stuff
$original_name = $file->getClientOriginalName();
$ext = strtolower($file->getClientOriginalExtension());
$size = $file->getSize();
$type = $file->getMimeType();

$hashName = $file->hashName();
 

If you have multiple files:

// $_FILES['filename']['name'] 'An associative array of items uploaded to the 
// current script via the HTTP POST method'
$files = $_FILES['filesarray']
for ($i = 0; $i < count($files['name']); $i++) {
    $name = $files['name'][$i];
    $file = new UploadedFile(
        $files['tmp_name'][$i],
        $name  
    );
    // Do stuff with file
};

For more on the PHP $_FILES array check the docs:

https://www.php.net/manual/en/features.file-upload.post-method.php

It worked for me when I removed 'Content-Type': 'multipart/form-data' from the http headers.

this.httpOptions = {
    headers: new HttpHeaders({
         'Accept': 'application/json',
         'Authorization': 'Bearer ' + this.apiToken
   })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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