在Heroku故障上使用laravel将多张图片上传到s3

在Heroku故障上使用laravel将多张图片上传到s3

本文介绍了在Heroku故障上使用laravel将多张图片上传到s3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历多个输入文件选择元素

I am trying to loop over a multiple input file select element

<label class="btn btn-success btn-md rounded-1" for="galleryFile">Create Album</label>
<input type="file" name="galleryFile[]" id="galleryFile" class="d-none" multiple accept="image/*">

并将所有选定的图像保存到AWS s3

and save all selected images to AWS s3

public function sendToCloud($file, $folder, $prefix) {
  $filePath = Auth::user()->userid . '/' .$folder.'/' . $prefix;

  $extension = $file->getClientOriginalExtension();
  $filename  = $filePath . time() . '.' . $extension;

  Storage::disk('s3')->put($filename, fopen($file, 'r+'), 'public');
  return Storage::disk('s3')->url($filename);
}

$unikPath = uniqid();
foreach ($request->file('galleryFile') as $key => $file) {
  if ($key == array_key_last($request->file('galleryFile'))) {
    $galleryUrl .= $this->sendToCloud($file, $unikPath . '/gallery', 'img_');
  } else {
    $galleryUrl .= $this->sendToCloud($file, $unikPath . '/gallery', 'img_') . ' | ';
  }
}

在我的本地计算机上,它可以很好地工作,使我相信这不是我的代码或laravel的问题,但是当我部署到heroku时,上传行为发生了变化.它在heroku上的作用是

On my local machine it works very fine making me believe its not a problem with my code or laravel alone but when I deployed to heroku the upload behavior changed. What it does on heroku is

我非常感谢您提供有关如何解决此问题的正确指导.

I appreciate any help pointing in the right direction on how to fix this issue.

提前谢谢.

推荐答案

在我发布此答案时,您已经写了一个答案来解释您的解决方案.但是,更好的解决方案是—

At the time I posted this answer, you had written an answer explaining your solution. However, a better solution is to—

  1. 使用 random_bytes (与 bin2hex 一起)而不是 uniqid 生成随机文件名,并且
  2. 检查是否已使用 fopen($ file,...)打开现有文件,如果是,则生成另一个文件名以避免覆盖现有文件.
  1. generate random file names using random_bytes (together with bin2hex) rather than uniqid, and
  2. check whether you have opened an existing file with fopen($file, ...), and if so, generate a different file name to avoid overwriting the existing one.

此外,您给出的解决方案也很脆弱-假设您的应用程序运行时系统时间永远不会改变,由于许多原因,包括服务器时钟同步,情况可能并非总是如此.另请参见 uniqid 的文档.

Also, the solution you give in your answer is fragile -- it assumes the system time will never be changed while your application is running, which may not always be the case for many reasons, including server clock synchronization. See also the documentation for uniqid.

这篇关于在Heroku故障上使用laravel将多张图片上传到s3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:16