php 当删除上传的图像,它触发存储按钮,而不是

7dl7o3gd  于 2023-04-04  发布在  PHP
关注(0)|答案(2)|浏览(119)

上传图片没有问题,但是当删除上传的图片时,它会触发存储按钮。我想知道为什么会发生这种情况?
控制器代码:

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', // max file size: 2MB
            'documents.*' => 'file|max:2048', // max file size: 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(),
            ]);

        // handle image uploads
        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();
                //$fileName = Str::slug($request['name']) . '-' . time() . '.' . $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++;
            }
        }
}
        return Redirect::route('produk.index');
    }

public function update(Request $request, $id)
    {
        $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', // max file size: 2MB
            'documents.*' => 'file|max:2048', // max file size: 2MB
        ]);

        DB::table('products')
            ->where('id', $id)
            ->update([
                '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_active' => $data['is_active'],
                'is_password' => $request['is_password'],
                'is_stamping' => $request['is_stamping'],
                'updated_at' => now(),
            ]);

        // handle image uploads
        if ($request->hasFile('images')) {
            //DB::table('product_images')->where('product_id', $id)->delete();
            //Storage::deleteDirectory('public/Product/Images/' . $id);
            foreach ($request->file('images') as $image) {
                $name = $request['name'] . '-' . $id;
                $now = new DateTime();
                $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $id . '.' . $image->getClientOriginalExtension();
                $path = $image->store('public/Product/Images/' . $fileName);
                DB::table('product_images')->insert([
                    'product_id' => $id,
                    'file_path' => Storage::url($path),
                    'created_at' => now(),
                ]);
            }
        }
return Redirect::route('produk.index');
    }

一旦按钮被触发,

const formik = useFormik({
        initialValues: {
            name: action === "create" ? "" : `${data.name}`,
            description: action === "create" ? "" : `${data.description}`,
            category_id: action === "create" ? "" : `${data.category_id}`,
            type_id: action === "create" ? "" : `${data.type_id}`,
            price: action === "create" ? "" : `${data.price}`,
            is_active: action === "create" ? "" : `${data.is_active}`,
            start_date: action === "create" ? "" : `${data.start_date}`,
            end_date: action === "create" ? "" : `${data.end_date}`,
            // is_password: action === "create" ? "" : `${data.is_password}`,
            // is_stamping: action === "create" ? "" : `${data.is_stamping}`,
        },
        validationSchema: validationSchema,

        onSubmit: async (values) => {
            try {
                switch (action) {
                    case "create":
                        await post(route("produk.store"));
                        Swal.fire({
                            text: "Maklumat produk berjaya disimpan",
                            icon: "success",
                        });
                        break;
                    case "update":
                        await put(route("produk.update", product.id), data);
                        Swal.fire({
                            text: "Maklumat produk berjaya dikemaskini",
                            icon: "success",
                        });
                        break;
                }
            } catch (error) {
                Swal.fire({
                    icon: "error",
                    title: "Oops...",
                    text: "Something went wrong!",
                });
            }
        },
    });

    return (
        <form method={"post"} onSubmit={formik.handleSubmit}>

                        ....................

删除按钮,用于删除添加产品时的文件上载

{/* Delete button to remove file upload when adding product */}
    const removeFileUpload = (e, index) => {
        const updatedFileUpload = [...fileUpload];
        updatedFileUpload.splice(index, 1);
        setFileUpload(updatedFileUpload);
        setData(name, updatedFileUpload);
    };

编辑/更新产品时删除img的删除按钮

return (
                   ...........
                    
{/* Delete Button when editing/update */}
        <button
           onClick={() => removeFileUpload(index)}
           className="outline-none border-none"
         >
           <FaTimes className="text-red-600" />
        </button>
.....
zf9nrax1

zf9nrax11#

最有可能的原因是按钮位于表单元素中,这会触发表单提交。

event.preventDefault();

添加到delete处理程序的事件侦听器,这样它就不会将事件冒泡到顶部元素,或者您可以将delete按钮移出表单标记

vmdwslir

vmdwslir2#

我找到了解决方案。我必须在点击按钮时创建一个新功能,

/* Delete documents button when updating/editing form*/
    const removeFileUpload2 = async (type) => {
        console.log("🚀 ~ removeFileUpload2 ~ type:", type);
        try {
            const fileType = type.file_path.endsWith(".pdf")
                ? "document"
                : "image";
            const routeName =
                fileType === "document"
                    ? "product-documents.destroy"
                    : "product-images.destroy";
            await Inertia.delete(route(routeName, type));
            Swal.fire(
                "Berjaya!",
                `Rekod jenis ${fileType} berjaya dipadam.`,
                "success"
            );
        } catch (error) {
            Swal.fire("Ralat!", error.response.data.message, "error");
        }
    }

然后用在按钮上

<span
         onClick={() => removeFileUpload2(file)}
         className="outline-none border-none cursor-pointer"
    >
         <FaTimes className="text-red-600" />
    </span>

相关问题