javascript 使用Remix处理服务器端文件

new9mtju  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(146)

我正在尝试使用表单将图像文件上传到CDN。我可以让它工作使用获取API,但我不想这样做的客户端。下面的方法似乎是正确的,但似乎不起作用。

export async function action({request}: ActionArgs) {
    const body = await request.formData();

    await fetch(`${API}/${body.get("fileName")}`, {
        method: 'PUT',
        body: body.get("file"),
        headers: {}
    }).then((response) => response.json());

    return json({});
}

export default function UploadImage() {
    const fetcher = useFetcher();
    
    const handleChange = async (e: any) => {
        const file = e.target.files[0];
        const fileData = new FormData();

        fileData.append('file', file);
        fileData.append('fileName', file.name);

        fetcher.submit(
            fileData,
            { method: 'POST' }
        );
    }

    return (
        <>
            <input type="file" onChange={handleChange} />
        </>
    );
}

我知道我应该使用unstableMultipartFormData,但文档没有解释如何编写上传处理程序的情况下,你会想上传文件到CDN。我发现的例子和教程似乎已经过时了,使用的是不再工作的旧版本。我甚至不确定上传者期望的参数或行为。
任何帮助将不胜感激!

j13ufse2

j13ufse21#

这个Remix示例应该向您展示这个过程。
https://github.com/remix-run/examples/tree/main/file-and-s3-upload
将S3上传处理程序替换为您自己的。

// utils/s3.server.ts

export const s3UploadHandler: UploadHandler = async ({
  name, // name is the `<input type="file" name="img">` so make sure you set that
  filename,
  data, // data is the file data as `AsyncIterable<Uint8Array>`
}) => {
  
  if (name !== "img") {
    return undefined;
  }
  const uploadedFileLocation = await uploadStreamToS3(data, filename!);
  return uploadedFileLocation;
};

https://github.com/remix-run/examples/blob/ba029da81459d1445d4756af86e573f507eeb43d/file-and-s3-upload/app/utils/s3.server.ts#L40-L50
以下是Remix类型

export type UploadHandlerPart = {
  name: string;
  filename?: string;
  contentType: string;
  data: AsyncIterable<Uint8Array>;
};

export type UploadHandler = (
  part: UploadHandlerPart
) => Promise<File | string | null | undefined>;

https://github.com/remix-run/remix/blob/e35569ed5334c0c00ea5ecfdd881ff9e2dfb290b/packages/remix-server-runtime/formData.ts#L4C1-L14C1

相关问题