在移动文件上的move_uploaded_file()之后调用PHP unlink()失败

问题描述 投票:0回答:2

我将上传到我服务器的文件发送到Amazon S3。为此,我:

  • 使用move_uploaded_file()将文件发送到temp-uploads文件夹。
  • 我使用S3 SDK将文件作为对象上传到S3。
  • 我使用unlink()删除文件。
  • unlink()失败,资源暂时无法使用

Windows Server运行PHP / Apache。

我可以在脚本运行完之后取消链接。在脚本外部调用unlink()命令会立即从服务器中删除该文件。我试图弄清楚如何从move_uploaded_file()发布文件,但在搜索一段时间后找不到任何东西。

我确实使用$thumb1 = new Imagick($filetothumbnail);并创建缩略图。但我接着说

$thumb1->clear();
$thumb1->destroy();

也许Imagick仍然打开文件?但是,我使用excel文件对此进行了测试,该文件没有制作缩略图,并且文件仍然无法从服务器中删除。

if(isset($_FILES['file'])){
  $name = $_FILES['file']['name'];
  $size = $_FILES['file']['size'];
  $tmp = $_FILES['file']['tmp_name'];
  $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));

  $newname = time().'_'.$j['id'].'_'.$name;
  $thumbname = 'tn_'.time().'_'.$j['id'].'_'.$name;
  move_uploaded_file($_FILES["file"]["tmp_name"], "temp-uploads/".$newname);

  //Now, generate thumbnail for the file:
  $filetothumbnail = $_SERVER['DOCUMENT_ROOT'].'/temp-uploads/'.$newname;
  $thumbnails = $_SERVER['DOCUMENT_ROOT'].'/temp-uploads/thumbs/';

  //Send to AWS Bucket
  $s3_filepath = 'project-assets/'.$newname;
  upload_s3_file($s3_filepath, "temp-uploads/".$newname);

  $filepath = s3url.$s3_filepath;

  if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif'){

  $thumb1 = new Imagick($filetothumbnail);
  $compression_type = Imagick::COMPRESSION_JPEG; 

  $thumb1->setImageCompression($compression_type); 
  $thumb1->setImageCompressionQuality(40);
  $thumb1->thumbnailImage(500, 0);
  $thumb1->setImageFormat('jpg');
  $thumb1->writeimage($thumbnails.$thumbname);
  $thumb1->clear();
  $thumb1->destroy();

  //If thumbnail is there. Only for certain file types.
  $s3_thumbpath = 'project-thumbnails/'.$thumbname;
  upload_s3_file($s3_thumbpath, "temp-uploads/thumbs/".$thumbname);

  unlink("temp-uploads/thumbs/".$thumbname); //Delete Thumbnail.

  $thumbpath = s3url.$s3_thumbpath;

  } else {
  $thumbpath = 0;
  }


  unlink("temp-uploads/".$newname); //Delete Uploaded File.
}

上传到S3功能是:

$s3Client = new S3Client([
  'version'     => 'latest',
  'region'      => 'us-east-2',
  'credentials' => [
     'key'    => s3key,
     'secret' => s3secret,
   ],
]);

$result = $s3Client->putObject([
  'Bucket' => 'bucketname',
  'Key' => $filename,
  'SourceFile' => $filepath,
]);
php imagick
2个回答
1
投票

快速浏览文档表明上传是异步的:

https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_promises.html

您应该使用承诺来创建一个回调,您可以在其中取消链接您的文件。链接中有很多代码示例。


0
投票

这篇文章帮我解决了这个问题:

https://stackoverflow.com/a/41537354/1766536

具体来说,我不得不使用fopen / fclose并使用Body而不是SourceFile上传

© www.soinside.com 2019 - 2024. All rights reserved.