简体   繁体   English

从 Angular 9 到 Laravel 的文件上传不起作用

[英]File upload from Angular 9 to Laravel not working

I am trying to upload image from angular 9 to Laravel .我正在尝试将图像从angular 9上传到Laravel I configured angular project in my local machine.我在本地机器上配置了 angular 项目。 And Laravel project is in another server.而 Laravel 项目在另一台服务器上。 I am using api calls to get data from larvel to angular.我正在使用 api 调用从 larvel 获取数据到 angular。 All are working fine but File upload is not working.一切正常,但文件上传不起作用。 The request get in server is null.(in usercontroller) Below is my code:进入服务器的请求是 null。(在用户控制器中)下面是我的代码:

Angular Angular

product.component.html [file upload form] product.component.html [文件上传表格]

<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] product.component.ts [文件更改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 Laravel

routes/api.php路线/api.php

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

UserController.php 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 uploadImage function 首先返回Select 图像

The request is getting as null in server.请求在服务器中获取为null

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.我最终使用了 PHP 文件数组。

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

import this class:导入这个 class:

use Illuminate\Http\UploadedFile;

then create a new UploadedFile;然后创建一个新的 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:有关 PHP $_FILES 数组的更多信息,请查看文档:

https://www.php.net/manual/en/features.file-upload.post-method.php 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.当我从 http 标头中删除 'Content-Type': 'multipart/form-data' 时,它对我有用。

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

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

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