我有一个带有 SAS 令牌的 URL,用于上传文件。我有一个先前定义的内容类型的 Base64 字符串,需要上传。
import { FileUploadStreamOptions, ShareFileClient } from "@azure/storage-file-share";
import { Readable } from "readable-stream";
async submitData(context: ComponentFramework.Context<IInputs>, fileName: string, ext: string, base64: string, contentType: string, classification: string, upload: any) : Promise<boolean> {
const buffer = Buffer.from(base64, 'base64');
let client = new ShareFileClient(upload.url);
let readable = Readable.from(buffer);
const options = {
fileHttpHeaders: {
fileContentType: contentType,
},
};
await client.uploadStream(readable, buffer.length, 4 * 1024 * 1024, 5, options);
console.log("Upload successful");
// more logic
return true;
}
我的代码有两个问题:
未等待
await client.uploadStream(readable, buffer.length, 4 * 1024 * 1024, 5, options);
,该方法已转义。
上传的文件已损坏。下载后,内容返回为:
{"$content-type":"application/pdf","$content":"AAAAAAAAAAAAAA...AAAAA"}
我尝试过不等待电话,这似乎在大多数情况下都有效,尽管确实应该等待。
我尝试向流中添加编码,但这似乎也不起作用。
我有一个带有 SAS 令牌的 URL,用于上传文件。我有一个先前定义的内容类型的 Base64 字符串,需要上传。
您可以使用以下代码将pdf文件上传到Azure文件共享中。
代码:
// upload.ts
import { ShareFileClient, FileUploadStreamOptions } from "@azure/storage-file-share";
import { Readable } from "stream";
async function submitData(fileName: string, base64: string, contentType: string, uploadUrl: string): Promise<boolean> {
try {
const buffer = Buffer.from(base64, 'base64');
const client = new ShareFileClient(uploadUrl);
const readable = Readable.from(buffer);
const options: FileUploadStreamOptions = {
fileHttpHeaders: {
fileContentType: contentType,
},
};
await client.uploadStream(readable, buffer.length, 4 * 1024 * 1024, 5, options);
console.log("Upload successful");
return true;
} catch (error) {
console.error("Upload failed:", error);
return false;
}
}
const main = async () => {
const fileName = "example.pdf"; // Set the file name
const contentType = "application/pdf"; // Set the content type
const uploadUrl = "https://<storage account name>.file.core.windows.net/<share name>/<filename>?sv=2022-11-02&ss=bfqt&srt=sco&sp=rwdlacupiytfx&se=2024-10-22T16:45:20Z&st=2024-10-22T08:45:20Z&spr=https&sig=redacted";
const base64 = "6xxxxx"
const result = await submitData(fileName, base64, contentType, uploadUrl);
console.log(`Upload result: ${result}`);
};
main().catch(console.error);
上面用
submitData
函数进行的解释是将 base64 字符串转换为 buffer
,创建 ShareFileClient
,并使用 uploadStream
方法上传文件。如果上传成功返回true
,否则返回false
。
输出:
Upload successful
Upload result: true
上面的代码成功上传了文件,当我上传后从门户点击
Download
时,它打开没有任何问题。