首页 > 解决方案 > 使用 Vue.js 项目将图像上传到 MS Azure

问题描述

我目前正在开发 VueJs 框架,我需要将我的项目连接到 Azure。但我不知道怎么做?我在 (firebase) 之前使用过的技术是否与我们为项目内部的存储添加配置的技术相同?

目前,我在 Azure 中创建了新的 blob 和容器,并且我得到了一个 saskey 和主要/次要路径.. 但我不确定下一步是什么?

同样在我的 VueJs 项目中,我添加了以下代码:

    var sasKey = '....'; //The code from the Azure
    var blobUri = '...'; //The path
    var blobService = AzureStorage.createBlobServiceWithSas(blobUri, sasKey).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());

      blobService.createBlockBlobFromText('ContainerName', 'BlobName', data,  function(error, result, response){
      if (error) {
          console.log('Upload filed, open browser console for more detailed info.');
          console.log(error);
      } else {
         console.log('Upload successfully!');
      }
    });

为了澄清我的问题,我是同时使用 Vue.js 和 Azure 的初学者。我需要知道帮助我成功将图像上传到 Azure 存储的正确步骤是什么。

另外,是否可以添加安全标头?就像我们在 Axios 中所做的那样?例如检查内容长度、内容类型等。

当我运行程序时,它总是打印:

Upload filed, open browser console for more detailed info. 
Error: XHR error
    at XMLHttpRequest.xhr.onerror

标签: javascriptazurevue.jsvuejs2

解决方案


首先我们需要允许 Azure 存储的 CORS,我们可以在 Azure 门户中进行设置:

在此处输入图像描述

下面是如何使用 javascript 将文件上传到 blob 的演示:

var blobUri = 'https://' + 'STORAGE_ACCOUNT' + '.blob.core.windows.net';
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, 'SAS_TOKEN');
// If one file has been selected in the HTML file input element
var file = document.getElementById('fileinput').files[0];

var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 512;
blobService.singleBlobPutThresholdInBytes = customBlockSize;

var finishedOrError = false;
var speedSummary = blobService.createBlockBlobFromBrowserFile('mycontainer', 
file.name, file, {blockSize : customBlockSize}, function(error, result, response) {
    finishedOrError = true;
    if (error) {
        // Upload blob failed
    } else {
        // Upload successfully
    }
});
refreshProgress();

供您参考的更多信息: 用于 Blob 操作的 Azure 存储 JavaScript 客户端库示例


推荐阅读