【发布时间】:2020-05-17 05:20:15
【问题描述】:
我最近尝试将我的 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。
上传的操作还是可以的,但是网上的文件就变成了乱码……
【问题讨论】:
-
虽然我可以看到您将内容编码设置为 gzip,但是您可以再次检查(作为健全性检查)吗?
-
@GauravMantri 我觉得逻辑是对的,通过这些方式上传的文件都可以不乱码读取(字体文件除外,天生就不能正常读取)。就是连线了,怎么打不开。
-
您能分享您的网站或其中一个文件的网址吗?
标签: javascript azure azure-blob-storage azure-sdk