【问题标题】:File upload from Angular 9 to Laravel not working从 Angular 9 到 Laravel 的文件上传不起作用
【发布时间】:2021-04-17 02:03:53
【问题描述】:

我正在尝试将图像从 angular 9 上传到 Laravel。 我在本地机器上配置了 Angular 项目。而 Laravel 项目在另一台服务器上。我正在使用 api 调用来获取从 larvel 到 angular 的数据。一切正常,但文件上传不起作用。 服务器中的请求为空。(在用户控制器中) 以下是我的代码:

角度

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 [文件更改功能和上传功能]

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

路由/api.php

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

用户控制器.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
  }
}

uploadImage 函数返回先选择图片

请求在服务器中获得为 null

我的代码有什么问题?我想有人可以帮助我..

【问题讨论】:

    标签: angular laravel file-upload


    【解决方案1】:

    我也有这个问题。我最终使用了 PHP 文件数组。

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

    导入这个类:

    use Illuminate\Http\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();
     
    

    如果您有多个文件:

    // $_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
    };
    

    有关 PHP $_FILES 数组的更多信息,请查看文档:

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

    【讨论】:

      【解决方案2】:

      当我从 http 标头中删除 'Content-Type': 'multipart/form-data' 时,它对我有用。

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

      【讨论】:

        猜你喜欢
        • 2016-03-24
        • 1970-01-01
        • 2021-02-03
        • 2017-07-28
        • 1970-01-01
        • 2018-06-11
        • 2019-07-05
        • 2014-11-04
        • 2021-01-02
        相关资源
        最近更新 更多