首页 > 解决方案 > 使用 Axios [VueJs] 将图像上传到 Azure Blob 容器

问题描述

我正在尝试使用 Axios PUT功能将图像上传到Azure Storage

我所做的如下:

  1. 我在 Azure 中创建了一个存储帐户,然后按如下方式添加了 CORS 规则:CORS 规则

  2. 我创建了一个带有 name 的 Blob user-pic

  3. 我使用Axios为我提出请求

代码:

function upload(formData) {

    //get the current date
    var currentdate = new Date(); 
    var Curr_date = currentdate.getDay + '-' + currentdate.getMonth + '-' + currentdate.getFullYear; 

    //Here I am trying to convert the image to binary encoding.
    var data = btoa(formData);

    //The image Url, [ below there is an example from where I take this url ].
    const url = "https://XXXXXXX.blob.core.windows.net/XXXXXXXXXXXX";

    //Headers are required for me, do I need to add all Headers in my code also in CORS of the storage account?
    axios.put(url, data {
          headers: {
            "Access-Control-Allow-Origin" : "*",
            'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
            "Access-Control-Allow-Headers": "Origin, Content-Type, x-ms-*",
            "Content-Type": "image/png",
            "Content-Length": data.length, //here I am trying to get the size of image.
            "x-ms-date": Curr_date,
            "x-ms-version": sv,
            "x-ms-blob-type": "BlockBlob",
          }            
        })
        .then ( response => { console.log(response); console.log('correct!!'); } )
        .catch ( error => { console.log(error); console.log('error here!!'); });
}

我的意思是代码中的注释:

  1. 图片 URL 的格式应与此相同:Blob SAS Url
  2. 的格式Curr_date是否正确可以被x-ms-date标头接受?
  3. 函数是否btoa用于将图像转换为二进制编码?
  4. 我应该将 Axios 中的所有标头添加到帐户存储 CORS(在标头字段中)吗?
  5. 获取图像大小的正确方法是什么?(.size函数?实际上,我formData在将所有图像附加到它之后传递。

运行程序后,在控制台中,我收到两条错误消息:错误信息

我该如何解决这些问题?

更新:

我做了这些改变:

  1. 我更改了 CORS:CORS
  2. 我收到此错误消息:错误消息

标签: javascripthtmlazurevue.jsvuejs2

解决方案


为 Azure 存储定义的 CORS 规则缺少http://localhost源。


推荐阅读