在Heroku故障上使用laravel将多张图片上传到s3 [英] Multiple image upload to s3 using laravel on heroku malfunction

查看:158
本文介绍了在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

如果我选择要上传的10张图片,它将随机选择其中2张图片并将其保存到s3,然后将这2张图片的s3网址返回10次.

if I selected 10 images to upload, it randomly picks and saves 2 of those images to s3 and return the s3 url of those 2 images 10 times.

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆