前回のつづき
前回の記事では、Uploadthing
を使ってNext.js
から画像をアップロードする手順を解説しました。↓
今回の記事ですること
この記事では、アップロードした画像(png,jpe,SVG etc...)をNext.js
を使って削除する方法を解説していきます。
サンプル
エクスプローラから画像を選択します。
正常にアップロードされると画面に画像が表示されます。
ダッシュボードを見ると、画像がアップロードされているのが分かります。
アラートを閉じると画像が消去されます。
Deleteボタンをクリックして、正常に削除されるとアラートが表示されます。
ダッシュボードをみると、アップロードした画像がちゃんと消去されています。
ディレクトリ構成
└── 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ファイルのダウンロードとオンライン圧縮サイト