我最近尝试将我的 Angular 站点部署到 Azure 静态网站,但发现了一些问题。
据我测试,使用 ng build 并将所有文件上传到 Blob 存储并且该站点运行良好,但是如果我压缩文件以节省更多空间,就会出错。
我在 Linux 下使用 gzip 压缩文件,最后将它们重命名为 clip .gz。
由于所有文件都编码为 gzip,我使用包 @azure/storage-blob 来上传我的文件,JS 中的脚本是这样的:
const fs = require("fs");
const {BlobServiceClient, StorageSharedKeyCredential} = require("@azure/storage-blob");
//Give every file type a content type
const contentTps = {
"js": "text/javascript",
"txt": "text/plain",
"png": "image/png",
"css": "text/css",
"json": "application/json",
"gif": "image/gif",
"ico": "image/x-icon",
"svg": "image/svg+xml",
"woff": "application/font-woff",
"html": "text/html"
};
//Should perhaps detect the key handly
const account = "accountName";
const accountKey = "accountKey";
const containerName = "$web";
const fileLocation = "./dist/";
// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only avaiable in Node.js runtime, not in browsers
let sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
let blobServiceClient = new BlobServiceClient(
`https://${account}.blob.core.windows.net`,
sharedKeyCredential
);
//This main function could be edited to fit others situations
async function main() {
//take container by container name
let container = blobServiceClient.getContainerClient(containerName);
//Delete all files in container , to upload it again.
for await (let blob of container.listBlobsFlat()) {
await container.deleteBlob(blob.name);
}
fs.readdirSync(fileLocation).forEach(file => {
console.log("file is " + file);
let stat = fs.lstatSync(fileLocation + "/" + file);
if (stat.isFile()) {
let txt = fs.readFileSync(fileLocation + "/" + file);
//test upload function.
let blobName = file;
let index = blobName.lastIndexOf(".");
let ext = blobName.substr(index + 1);
console.log("The file end with:" + ext);
console.log("Uploading block blob" + blobName);
//should edit content type when upload, otherwise they will all become application/octet-stream, and impossible to open in browser
container.uploadBlockBlob(blobName, txt, txt.length, {
"blobHTTPHeaders": {
"blobContentType":contentTps[ext],
//not for local deploy test"blobContentEncoding":"gzip"
blobContentEncoding: "gzip",
}
});
//const uploadResponse = blockBlobClient.uploadFile(fileLocation+"/"+file);
console.log("Blob was uploaded ");
}
});
}
main();
如您所见,我还将 content-type 更改为对应的类型,而不是默认情况下的 application/octet-stream。
上传的操作还是可以的,但是网上的文件就变成了乱码……