首页 > 解决方案 > 如何在 laravel->move() 函数中修复文件上传图像

问题描述

我尝试使用文件图像上传图像但显示此错误

=> Symfony\Component\HttpFoundation\File\Exception\FileException
Could not move the file "C:\xampp\tmp\phpB3DB.tmp" to "works_images\2020-06-25 08:35:57before.jpg" (move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpB3DB.tmp' to 'works_images\2020-06-25 08:35:57before.jpg').

我在 Tratis 中使用此代码上传图片有什么错误?

public function saveImage($imgBefore , $imgAfter , $folder){
   $file_extention1 = $imgBefore->getClientOriginalExtension();
   $file_extention2 = $imgAfter->getClientOriginalExtension();

   $fileName1 = Carbon::now()->toDateTimeString().'before.'.$file_extention1;
   $fileName2 = Carbon::now()->toDateTimeString().'after.'.$file_extention2;

   $path = $folder;

   $imgBefore->move($path , $fileName1);
   $imgAfter->move($path , $fileName2);
   return [$fileName1,$fileName2]; }

标签: phplaravel

解决方案


使用文件名中的保留字符会出现此问题

这是您获取文件名的方式:

$fileName1 = Carbon::now()->toDateTimeString().'before.'.$file_extention1;
$fileName2 = Carbon::now()->toDateTimeString().'after.'.$file_extention2;
// Output
// 2020-06-25 08:35:57before.jpg

这意味着最终的文件名将包含-, :blank space. 在阅读这篇维基百科文章https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words时,意识到:(冒号)是一个保留字符,一旦你去掉它(通过修改时间戳部分,如date('Ymd_His')

试试这个 :

$fileName1 = Carbon::now()->format('Y-m-d_H-i-s').'before.'.$file_extention1;
$fileName2 = Carbon::now()->format('Y-m-d_H-i-s').'after.'.$file_extention2;

推荐阅读