0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ファイルストレージサービスである【UploadThing】でNext.jsから画像を削除する方法

Posted at

前回のつづき

前回の記事では、Uploadthingを使ってNext.jsから画像をアップロードする手順を解説しました。↓

今回の記事ですること

この記事では、アップロードした画像(png,jpe,SVG etc...)をNext.jsを使って削除する方法を解説していきます。

サンプル

エクスプローラから画像を選択します。

image.png

正常にアップロードされると画面に画像が表示されます。

image.png

ダッシュボードを見ると、画像がアップロードされているのが分かります。

image.png

アラートを閉じると画像が消去されます。

image.png

Deleteボタンをクリックして、正常に削除されるとアラートが表示されます。

image.png

ダッシュボードをみると、アップロードした画像がちゃんと消去されています。

image.png

ディレクトリ構成

└── Procject/
    └── app/
        ├── api/
        │   ├── action/
        │   │   └── imageRemove.ts
        │   └── server/
        │       └── uploadthing.ts
        └── components/
            └── thumbnailUploadthing/
                └── page.tsx

実装

フロント画面に実装

Project/app/components/thumbnailUploadthing/page.tsx
"use client";
 
// You need to import our styles for the button to look right. Best to import in the root /layout.tsx but this is fine
import "@uploadthing/react/styles.css";
 
import { UploadButton } from "@uploadthing/react";
//import { OurFileRouter } from "./api/uploadthing/core";
import { OurFileRouter } from "@/app/api/uploadthing/core";
import { useState } from "react";
import { imageRemove } from "@/app/api/action/imageRemove";
 
export default function Home() {
  const [file,setFile] = useState<string | null>(null);
  const [imageKey,setImageKey] = useState('');

  const clickImageDelete = async()=>{
    const response = await imageRemove(imageKey);
    if(response.success){
        alert('Your uploaded file was removed from server.');
        setFile("");
        setImageKey("");
    }
  }

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
        <div className="w-full border border-gray-500 rounded-md px-8 py-4">
            <h2 className="flex justify-center font-bold">Please upload your thumbnail.</h2>
            
            {file && (
                <div>
                    <div className="flex justify-center mt-4 mb-4">
                        <img
                            className="w-100 h-100 rounded-full border border-gray-500"
                            alt="rounded-avator" 
                            src={file}
                        />
                    </div>
                    <div className="flex justify-center">
                        <button
                            type="button"
                            className="bg bg-rose-500 text-white rounded-md px-4 py-4"
                            onClick={clickImageDelete}
                            >
                            Delete
                        </button>
                    </div>
                </div>
            )}
            
            <UploadButton<OurFileRouter>
                endpoint="imageUploader"
                onClientUploadComplete={(res) => {
                // Do something with the response
                console.log("Files: ", res);
                setFile(res[0].url);
                setImageKey(res[0].key);
                alert("Upload Completed");
                }}
                onUploadError={(error: Error) => {
                // Do something with the error.
                alert(`ERROR! ${error.message}`);
                }}
            />
        </div>
    </main>
  );
}

サーバ側の実装

Project/app/api/action/imageRemove.ts
"use server"
import { utapi } from "../server/uploadthing"

export const imageRemove = async(imageKey:string)=>{
    try{
        await utapi.deleteFiles(imageKey);
        return {success:true};
    }catch(error){
        return {success:false};
    }
}
Project/app/api/server/uploadthing.ts
import { UTApi } from "uploadthing/server";

export const utapi = new UTApi();

以上です。

参考サイト

■Next.js 14 + Uploadthing : Image Preview and Delete From Server | EzyCode

SVGファイルのダウンロードとオンライン圧縮サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?