javascript - 使用 Deno 模組 deno-s3-lite-client 上傳檔案到 S3 存儲桶
我一直在嘗試使用 Deno 的 s3 lite 客戶端來製作一個文件上傳控制器,但我在上傳文件的內容類型時遇到了一個問題。在他們的文檔中,我可以看到使用 putObject() 函數的方式如下:
Deno.test({
name: "putObject() can stream a large file upload",
fn: async () =\> {
// First generate a 32MiB file in memory, 1 MiB at a time, as a stream
const dataStream = ReadableStream.from(async function\* () {
for (let i = 0; i \< 32; i++) {
yield new Uint8Array(1024 \* 1024).fill(i % 256); // Yield 1MB of data
}
}());
// Upload the 32MB stream data as 7 5MB parts. The client doesn't know in advance how big the stream is.
const key = "test-32m.dat";
const metadata = { "Content-Type": "test/streaming", "x-amz-meta-custom-header": "This is a custom value!" };
const response = await client.putObject(key, dataStream, { partSize: 5 * 1024 * 1024, metadata });
// The etag is generated by the server, based on the contents. Also, etags for multi-part uploads are
// different than for regular uploads, so the "-7" confirms it worked and used a multi-part upload.
assertEquals(response.etag, "ca6d977b6e7dc87ab5c5892e124c7277-7");
// Validate that the metadata was set:
const stat = await client.statObject(key);
assertEquals(stat.metadata, metadata);
},
});
而在我的程式碼中,我是這樣寫的:
export async function uploadFileToS3(
companyId: string,
categoryId: string,
dppId: string | null,
fileData: File,
fileName: string,
fileType: string,
): Promise\<string\> {
if (!fileData) {
throw new Error("File data is undefined or null");
}
console.log("Uploading file to S3:", fileData.type); // Debugging line
try {
// Read the file as an ArrayBuffer
const buffer = await fileData.arrayBuffer();
// Convert ArrayBuffer to Uint8Array
const fileArrayBuffer = new Uint8Array(buffer);
let filePath = "";
if (fileType === "categoryImage") {
filePath = `companies/${companyId}/categories/${categoryId}/category-image/${fileName}`;
} else if (fileType === "dppFile") {
filePath = `companies/${companyId}/categories/${categoryId}/dpps/${dppId}/${fileName}`;
} else if (fileType === "modelFile") {
filePath = `companies/${companyId}/categories/${categoryId}/models/${fileName}`;
}
// Debugging log for filePath
console.log("Uploading file to S3 with filePath:", filePath);
// Use contentType option to set the Content-Type header directly
const metadata = {
"Content-Type": fileData.type,
};
// Upload the file using the S3 client
await s3Client.putObject(filePath, fileArrayBuffer, { metadata});
console.log("Upload successful");
// Verify the uploaded file's metadata
const stat = await s3Client.statObject(filePath);
console.log("Uploaded file metadata:", stat.metadata);
return filePath;
} catch (error) {
console.error("Error uploading to S3:", error);
throw error;
}
}
你能從這裡看出問題出在哪裡嗎?我成功上傳了檔案,但它在 S3 儲存桶中的類型是空的,而且我無法打開它,因為它有這個問題。
我已經嘗試以多種方式組合內容類型,但都沒有用。