实现下载功能,但出现 404 错误(laravel)

huangapple go评论63阅读模式
英文:

Implementing download functionality but getting a 404 error ( laravel )

问题

我正在尝试在我的代码中实现“下载所有文件”的功能。我已经参考了一些StackOverflow上的链接来实现这个功能。然而,我仍然在努力使其工作,以下是下载控制器,

public function downloadDocuments($id)
{
    $documents = DB::table('product_documents')->where('id', $id)->first();
    $path2 = $documents->file_path;
    $files = array(Storage::url($path2));
    $zip = new ZipArchive();
    $zip_name = time() . "documents.zip"; // 压缩文件名
    $zip->open($zip_name,  ZipArchive::CREATE);
    foreach ($files as $file) {
        echo $path = "public/Product/Documents/" . $file;
        if (file_exists($path)) {
            $zip->addFromString(basename($path),  file_get_contents($path));
        } else {
            echo "文件不存在";
        }
    }
    $zip->close();
}

这是“下载”按钮和路由,

<Link href="product-documents.download">
    <span
        className="flex items-center justify-center"
        data-tooltip-id="my-tooltip"
        data-tooltip-content="下载文件"
    >
    <DocumentArrowDownIcon className="h-4 w-4" />
    </span>
</Link>

路由如下,

Route::get('/download-documents', [ProductsController::class, 'downloadDocuments'])->name('product-documents.download');

以下是存储所有文档/图片的控制器。为了试验,我只想下载多个文档文件。我一遍又一遍地尝试,但它一直失败。请告诉我如何修复这个问题?谢谢

public function store(Request $request)
{
    $data = $this->validate($request, [
        'name' => 'required',
        'description' => 'required|max:150',
        'category_id' => 'required',
        'type_id' => 'required',
        'price' => 'required|numeric|min:0|not_in:0',
        'start_date' => 'required',
        'end_date' => 'required',
        'is_active' => 'required',
        'images.*' => 'image|max:2048', // 文件最大尺寸: 2MB
        'documents.*' => 'file|max:2048', // 文件最大尺寸: 2MB
    ]);

    $product = DB::table('products')
        ->insertGetId([
            'name' => $data['name'],
            'description' => $data['description'],
            'type_id' => $data['type_id'],
            'category_id' => $data['category_id'],
            'price' => $data['price'],
            'start_date' => $data['start_date'],
            'end_date' => $data['end_date'],
            'is_password' => $request['is_password'],
            'is_stamping' => $request['is_stamping'],
            'created_at' => now(),
        ]);

    // 处理图片上传
    if ($request->hasFile('images')) {
        $i = 1;
        foreach ($request->file('images') as $image) {
            $name = $request['name'] . '-' . $i;
            $now = new DateTime();
            $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $i . '.' . $image->getClientOriginalExtension();
            $path = $image->storeAs('public/Product/Images', $fileName);
            DB::table('product_images')->insert([
                'product_id' => $product,
                'name' => $name,
                'file_path' => Storage::url($path),
                'created_at' => now(),
            ]);
            $i++;
        }
    }

    // 处理文档上传
    if ($request->hasFile('documents')) {
        $i = 1;
        foreach ($request->file('documents') as $document) {
            $name = $request['name'] . '-' . $i;
            $now = new DateTime();
            $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $i . '.' . $document->getClientOriginalExtension();
            $path = $document->storeAs('public/Product/Documents', $fileName);
            DB::table('product_documents')->insert([
                'product_id' => $product,
                'name' => $name,
                'file_path' => Storage::url($path),
                'created_at' => now(),
            ]);
            $i++;
        }
    }

    $now = Carbon::now();
    $month = $now->format('m');
    $year = $now->format('Y');

    DB::table('log_audits')->insert([
        'module_name' => 'Jualan',
        'description' => 'Simpan Produk ' . $data['name'],
        'user_id' => auth()->user()->id,
        'created_at' => $now,
        'month' => $month,
        'year' => $year,
    ]);
    return Redirect::route('produk.index');
}

一开始,我尝试实现Zipper/Chumper方法,但它不起作用,因为这个Web应用程序运行在Laravel 7而不是Laravel 5上。然后我进行了一些研究,发现可以使用ZipArchive。在编写代码并尝试运行后,我得到了404错误。我确信我可能在我的代码中漏掉了一些东西,或者可能我错误地编写和引用了它。请帮忙。

英文:

I am trying to implement download all files functionality in my code. I've referred to some links in stackoverflow to implement this. However, I am still struggling to make this works, below are the download controller,

public function downloadDocuments($id)
{
$documents = DB::table(&#39;product_documents&#39;)-&gt;where(&#39;id&#39;, $id)-&gt;first();
$path2 = $documents-&gt;file_path;
$files = array(Storage::url($path2));
$zip = new ZipArchive();
$zip_name = time() . &quot;documents.zip&quot;; // Zip name
$zip-&gt;open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = &quot;public/Product/Documents/&quot; . $file;
if (file_exists($path)) {
$zip-&gt;addFromString(basename($path),  file_get_contents($path));
} else {
echo &quot;file does not exist&quot;;
}
}
$zip-&gt;close();
}

Here is the button and route for the download,

&lt;Link href=&quot;product-documents.download&quot;&gt;
&lt;span
className=&quot;flex items-center justify-center&quot;
data-tooltip-id=&quot;my-tooltip&quot;
data-tooltip-content=&quot;Download dokumen&quot;
&gt;
&lt;DocumentArrowDownIcon className=&quot;h-4 w-4&quot; /&gt;
&lt;/span&gt;
&lt;/Link&gt;
Route::get(&#39;/download-documents&#39;, [ProductsController::class, &#39;downloadDocuments&#39;])-&gt;name(&#39;product-documents.download&#39;);

Below are the controller when storing all the documents/images. For experiment, I only want to download multiple files of the documents. I tried again and again but it keeps on failing. Please tell me how can I fix this ? Thank you

public function store(Request $request)
{
$data = $this-&gt;validate($request, [
&#39;name&#39; =&gt; &#39;required&#39;,
&#39;description&#39; =&gt; &#39;required|max:150&#39;,
&#39;category_id&#39; =&gt; &#39;required&#39;,
&#39;type_id&#39; =&gt; &#39;required&#39;,
&#39;price&#39; =&gt; &#39;required|numeric|min:0|not_in:0&#39;,
&#39;start_date&#39; =&gt; &#39;required&#39;,
&#39;end_date&#39; =&gt; &#39;required&#39;,
&#39;is_active&#39; =&gt; &#39;required&#39;,
&#39;images.*&#39; =&gt; &#39;image|max:2048&#39;, // max file size: 2MB
&#39;documents.*&#39; =&gt; &#39;file|max:2048&#39;, // max file size: 2MB
]);
$product = DB::table(&#39;products&#39;)
-&gt;insertGetId([
&#39;name&#39; =&gt; $data[&#39;name&#39;],
&#39;description&#39; =&gt; $data[&#39;description&#39;],
&#39;type_id&#39; =&gt; $data[&#39;type_id&#39;],
&#39;category_id&#39; =&gt; $data[&#39;category_id&#39;],
&#39;price&#39; =&gt; $data[&#39;price&#39;],
&#39;start_date&#39; =&gt; $data[&#39;start_date&#39;],
&#39;end_date&#39; =&gt; $data[&#39;end_date&#39;],
&#39;is_password&#39; =&gt; $request[&#39;is_password&#39;],
&#39;is_stamping&#39; =&gt; $request[&#39;is_stamping&#39;],
&#39;created_at&#39; =&gt; now(),
]);
// handle image uploads
if ($request-&gt;hasFile(&#39;images&#39;)) {
$i = 1;
foreach ($request-&gt;file(&#39;images&#39;) as $image) {
$name = $request[&#39;name&#39;] . &#39;-&#39; . $i;
$now = new DateTime();
$fileName = Str::slug($request[&#39;name&#39;]) . &#39;-&#39; . $now-&gt;format(&#39;dmYHis&#39;) . &#39;-&#39; . $i . &#39;.&#39; . $image-&gt;getClientOriginalExtension();
//$fileName = Str::slug($request[&#39;name&#39;]) . &#39;-&#39; . time() . &#39;.&#39; . $image-&gt;getClientOriginalExtension();
$path = $image-&gt;storeAs(&#39;public/Product/Images&#39;, $fileName);
DB::table(&#39;product_images&#39;)-&gt;insert([
&#39;product_id&#39; =&gt; $product,
&#39;name&#39; =&gt; $name,
&#39;file_path&#39; =&gt; Storage::url($path),
&#39;created_at&#39; =&gt; now(),
]);
$i++;
}
}
// handle document uploads
if ($request-&gt;hasFile(&#39;documents&#39;)) {
$i = 1;
foreach ($request-&gt;file(&#39;documents&#39;) as $document) {
$name = $request[&#39;name&#39;] . &#39;-&#39; . $i;
$now = new DateTime();
$fileName = Str::slug($request[&#39;name&#39;]) . &#39;-&#39; . $now-&gt;format(&#39;dmYHis&#39;) . &#39;-&#39; . $i . &#39;.&#39; . $document-&gt;getClientOriginalExtension();
//$fileName = Str::slug($request[&#39;name&#39;]) . &#39;-&#39; . time() . &#39;.&#39; . $document-&gt;getClientOriginalExtension();
$path = $document-&gt;storeAs(&#39;public/Product/Documents&#39;, $fileName);
DB::table(&#39;product_documents&#39;)-&gt;insert([
&#39;product_id&#39; =&gt; $product,
&#39;name&#39; =&gt; $name,
&#39;file_path&#39; =&gt; Storage::url($path),
&#39;created_at&#39; =&gt; now(),
]);
$i++;
}
}
$now = Carbon::now();
$month = $now-&gt;format(&#39;m&#39;);
$year = $now-&gt;format(&#39;Y&#39;);
DB::table(&#39;log_audits&#39;)-&gt;insert([
&#39;module_name&#39; =&gt; &#39;Jualan&#39;,
&#39;description&#39; =&gt; &#39;Simpan Produk &#39; . $data[&#39;name&#39;],
&#39;user_id&#39; =&gt; auth()-&gt;user()-&gt;id,
&#39;created_at&#39; =&gt; $now,
&#39;month&#39; =&gt; $month,
&#39;year&#39; =&gt; $year,
]);
return Redirect::route(&#39;produk.index&#39;);
}

At first I tried to implement the Zipper/Chumper method but it's not working since this web app run on laravel 7 instead of laravel 5. So then I did some research and found that I can use ZipArchive. After writing the code and tried to run it. I get the 404 error. I am sure that I may have missed something in my code or probably I wrote and referenced it to the wrong things. Please help

答案1

得分: 2

I think there are multiple problems in your code.

First is that the <Link> component doesn't accept a route name but a path.
To use a route name you need to use the Ziggy route() helper.

You can try with :

<Link :href="route('product-documents.download')">
    <span
        className="flex items-center justify-center"
        data-tooltip-id="my-tooltip"
        data-tooltip-content="Download dokumen"
    >
    <DocumentArrowDownIcon className="h-4 w-4" />
    </span>
</Link>

or

<Link href="/download-documents)">
    <span
        className="flex items-center justify-center"
        data-tooltip-id="my-tooltip"
        data-tooltip-content="Download dokumen"
    >
    <DocumentArrowDownIcon className="h-4 w-4" />
    </span>
</Link>

Second is that currently your downloadDocuments($id) function requires an id which you are not setting (and which you should not need to download all the documents).

英文:

I think there are multiple problems in your code.

First is that the &lt;Link&gt; component doesn't accept a route name but a path.
To use a route name you need to use the ziggy route() helper.

You can try with :

&lt;Link :href=&quot;route(&#39;product-documents.download&#39;)&quot;&gt;
    &lt;span
        className=&quot;flex items-center justify-center&quot;
        data-tooltip-id=&quot;my-tooltip&quot;
        data-tooltip-content=&quot;Download dokumen&quot;
    &gt;
    &lt;DocumentArrowDownIcon className=&quot;h-4 w-4&quot; /&gt;
    &lt;/span&gt;
&lt;/Link&gt;

or

&lt;Link href=&quot;/download-documents&#39;)&quot;&gt;
    &lt;span
        className=&quot;flex items-center justify-center&quot;
        data-tooltip-id=&quot;my-tooltip&quot;
        data-tooltip-content=&quot;Download dokumen&quot;
    &gt;
    &lt;DocumentArrowDownIcon className=&quot;h-4 w-4&quot; /&gt;
    &lt;/span&gt;
&lt;/Link&gt;

Second is that currently your downloadDocuments($id) function requires an id which you are not setting (and which you should not need to downlaod all the documents).

huangapple
  • 本文由 发表于 2023年4月4日 12:05:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定