next.js 正在删除文件

pzfprimi  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(110)

我如何删除文件从madthing?(NextJS 13)
目前我是这样尝试的:
-> src/server/delete.ts

import { UTApi } from "uploadthing/server"

export const utapi = new UTApi();

字符串
-> src/server/deleteImage.js

import React from 'react'
import { utapi } from './delete'

const deleteImage = () => {

    const testDelete = async () => {
        console.log("delete files")
        const res = await utapi.deleteFiles("b0e3a5bc-dd85-40fe-9a0c-59d2ece0bb60-4ulhix.png");
        console.log(res)
    }

    return (
        <div>
            <h1>test image delete</h1>
            <button onClick={testDelete}>Delete files</button>
        </div>
    )
}

export default deleteImage


然后我尝试从客户端组件调用它,如下所示:

<DeleteImage />


但是,我得到错误:“Uncaught(in promise)Error:The utapi can only be used on the server.”
有没有什么好的例子来说明如何在上传时删除文件?
提前感谢!

6vl6ewon

6vl6ewon1#

它为我工作:

export const { GET, POST } = createNextRouteHandler({
  router: ourFileRouter,
});

export async function DELETE(request: Request) {
  const data = await request.json();
  const newUrl = data.url.substring(data.url.lastIndexOf("/") + 1);
  const utapi = new UTApi(); --- i used this inside route file in uploadthing folder
  await utapi.deleteFiles(newUrl);

  return Response.json({ message: "ok" });
}

字符串
这是我在客户端组件中的删除函数:

const deleteValue = async () => {
    await axios.delete("api/uploadthing", {
      data: {
        url: value,
      },
    });
  };

相关问题