首页 文章

如何使用php laravel将图像上传到服务器?

提问于
浏览
0

我've been trying to write an api to upload image to server ,but all in vain. I'米使用laravel框架 . 并尝试了this example但它无法正常工作 .

同时在测试POSTMAN的api时,我已经在Headers中传递了mutlipart / form-data . 并在Body选项卡中选择了form-data,添加了key = image,将其更改为Text to File并添加了一个image.But当我测试时api,不知道为什么但是图像请求是空的 .

也许我可能在POSTMAN中传递错误或我的代码可能有问题,请帮助我 .

这是我的api代码

public function upload(Request $request){

if ($request->hasFile('image')) {
   $image = $request->file('image');
   $name = md5(time().uniqid()).".png";
   $destinationPath = base_path() . '/public/uploads/images/' . $name;

   move_uploaded_file($name, $destinationPath);

   return response()->json(['title'=>"image is uploaded"]);
   }

}

我的控制器代码:

Route::post('uploadImage','TestController@upload');

邮递员请求的屏幕截图 . 如果我在 Headers 或正文中传递错误,请告诉我 .

enter image description here

此外,控制台显示此错误 Missing boundary in multipart/form-data POST data in Unknown on line 0

1 回答

  • 1

    您可以使用核心PHP代码进行文件上载 . 在我的laravel项目中,我使用以下代码上传文件 .

    if(isset($_FILES["image"]["type"]))
    {
      $FILES = $_FILES["image"];
      $upload_dir = storage_path('app/public/document/');
    
      // create folder if not exists
      if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
      }
    
      //Send error 
      if ($FILES['error'])
      {
        return response()->json(['error'=>'Invalid file']);
      }
    
      //Change file name
      $target_file = md5(time().uniqid());
      $imageFileType = pathinfo($FILES["name"],PATHINFO_EXTENSION);
      $target_file = $upload_dir.$target_file.'.'.$imageFileType;
    
      //Upload file
      if (move_uploaded_file($FILES["tmp_name"], $target_file))
      {
        return response()->json(['success' => 'File uploading successful']);
      }
      else
      {
        return response()->json(['error'=>'Invalid file']);
      }
    }else{
     return response()->json(['error'=>'Invalid file']);
    }
    

    下面是我在函数
    enter image description here
    开头打印$ _FILES时的屏幕截图

相关问题