我最近尝试将我的 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();
如您所见,我还将内容类型更改为对应的内容类型,而不是默认的 application/octet-stream。
上传操作还可以,但是网上的文件就变成乱码了...
最佳答案
您需要先压缩内容。这是一个例子
const content = "Hello world hello world Hello world hello world Hello world hello world";
const gzipped = zlib.gzipSync(content);
const res = await blockBlobClient.upload(gzipped, gzipped.byteLength, {
blobHTTPHeaders: {
blobContentEncoding: "gzip",
blobContentType: "text/plain; charset=UTF-8"
}
})
关于javascript - Azure Blob 静态网站中的乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60005570/