Laravel实现批量压缩下载

Laravel 86℃ 0评论

码农宅

附加的批量下载

由于项目的需求,要对图片和附件实现批量压缩下载,经过几个小时的研究,调试终于搞出来了,代码实现,大神可以绕过,不要绕过了可以根据我的逻辑,写出自己的代码。。。直接贴代码。

public function download()
{
    $user = \Auth::user();
    //验证字段
    $request = array_filter($this->request->input());
    array_walk($request, function (&$value, $key) {
        if (is_array($value)) {
            $value = array_filter($value);
        }
    });

    $validator = \Validator::make($request, [
        'attachment_ids' => 'required|array|min:1',
    ]);

    if ($validator->fails()) {
        return $this->errorBadRequest($validator->messages()->all());
    }

    $attachmentIds = $this->request->get('attachment_ids');

    $attachments = Attachment::whereIn('id', $attachmentIds)->get();

    if (!$attachments->count()) {
        return $this->response->errorNotFound();
    }

    if ($attachments->count() == 1) {
        $attachment = $attachments->first();

        if (!$attachment->allowDownload($user)) {
            return $this->response->errorForbidden();
        }

        return response()->download(public_path($attachment->relative_path));
    } else {
        $zip = new \ZipArchive();
        $zipFile = storage_path('app/cache/' . date('Ymdhis') . uniqid() . '.zip');

        $zip->open($zipFile, \ZIPARCHIVE::CREATE);

        foreach ($attachments as $attachment) {
            if (!$attachment->allowDownload($user)) {
                continue;
            }

            $filename = basename($attachment->relative_path);

            $zip->addFile($attachment->relative_path, $filename);
        }
        $zip->close();

        return response()->download($zipFile);
    }
}

代码也是非常的简单,

转载请注明:码农宅 » Laravel实现批量压缩下载

喜欢 (0)or分享 (0)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址